【发布时间】:2018-05-18 03:55:09
【问题描述】:
我有一个数组,其中包含我试图合并在一起的类似索引。由于某种原因,我无法理解它。
原始数组
$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
}
【问题讨论】:
-
它有没有可能拥有另一个维度?
-
@pr1nc3 只会有 tier1-4 的索引,但值可能完全不同