我有一个类似索引的数组,我试图合并在一起。出于某种原因,我无法绕过它。
$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);
{
"Group1": {
"Blue": {
"Round": [
"Harold",
"Arthur",
"Tom"
]
}
},
"Group2": {
"Blue": {
"Round": [
"Peter"
]
}
}
}
这是我目前所处的位置,但我不知道我是否朝着正确的方向前进。
$newCombined = array();
//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {
if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
//.. and so on
}
答案 0 :(得分:2)
如果只有select L.MemberNo, A.FirstName
FROM Booking.Loans as L
INNER JOIN Article.Items as I
on L.ISBN = I.ISBN
INNER JOIN Article.TitleAuthors as TA
on I.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID
可以产生一个数组,那么循环和分配就很简单了(如果您对沉默通知没问题):
tier4
使作业变得不那么神秘:
$array = json_decode('...', true);
$new = [];
foreach ($array as $e)
@$new[$e['tier1']][$e['tier2']][$e['tier3']][] = $e['tier4'];
echo json_encode($new, JSON_PRETTY_PRINT); # to print what you asked for
从foreach ($array as $e) {
list($t1, $t2, $t3, $t4) = array_values($e);
@$new[$t1][$t2][$t3][] = $t4;
}
返回到原始数组:
$new
答案 1 :(得分:1)
Sidyll的回答很完美,但在我自己的解决方案上,我也会发布它:
$input = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);
$output = [];
foreach($input as $row) {
$recursion = &$output;
foreach($row as $key => $value) {
if ($key != 'tier4' && !isset($recursion[$value])) {
$recursion[$value] = [];
}
if ($key == 'tier4') {
$recursion[] = $value;
} else {
$recursion = &$recursion[$value];
}
}
}
var_dump($output);
array(3){[" Group1"] => array(1){[" Blue"] => array(1){[" Round"] => array(3){[0] =>字符串(6)"哈罗德" [1] => string(6)" Arthur" [2] => string(3)" Tom" }" Group2"] => array(1){[" Blue"] => array(1){[" Round"] => array(1){[0] => string(4)" Beth" }" Group3"] => array(1){[" Blue"] => array(1){[" Round"] => & array(1){[0] =>字符串(5)"彼得" }}}
不是特别自豪,但它确实有效。