嵌套数组。 第三层正在消失
我有这个数组:
$a = array( "7" => array( "id" => 7, "parent" => 6 ), "6" => array( "id" => 6, "parent" => 5 ), "5" => array( "id" => 5, "parent" => 4 ), "4" => array( "id" => 4, "parent" => 0 ), "3" => array( "id" => 7, "parent" => 2 ), "2" => array( "id" => 7, "parent" => 1 ), "1" => array( "id" => 7, "parent" => 0 ) );
我想要的结果是:
$a = array( "4" => array( "id" => 4, "parent" => 0, array( "5" => array( "id" => 5, "parent" => 4, array( "6" => array( "id" => 6, "parent" => 5, array( "7" => array( "id" => 7, "parent" => 6 ) ) ) ) ) ) ), "2" => array( "id" => 7, "parent" => 1, array( "3" => array( "id" => 7, "parent" => 2 ) ) ), "1" => array( "id" => 7, "parent" => 0 ) );
我使用的代码是这样的:
foreach($a as $v) { if(isset($a[$v['PARENT']])) { $a[$v['PARENT']][$v['ID']] = $v; unset($a[$v['ID']]); } }
而我所遇到的问题是我得到了这样的结果:
$a = array( "4" => array( "id" => 4, "parent" => 0, array( "5" => array( "id" => 5, "parent" => 4 ) ) ), "2" => array( "id" => 7, "parent" => 1, array( "3" => array( "id" => 7, "parent" => 2 ) ) ), "1" => array( "id" => 7, "parent" => 0 ) );
而不是需要它的结果。
为了解决你的问题,你需要正确理解PHP中的variables引用/别名是如何工作的。
看下面的示例代码,与您的代码看起来没有什么不同,但是使用引用来访问任何父代,即使它已经“移动”了:
# transform $flat into a tree: foreach($flat as $id => &$value) { # check if there is a parent if ($parentId = $value['parent']) { $flat[$parentId][0][$id] =& $value; # add child to parent unset($flat[$id]); # remove reference from topmost level } } unset($value); # remove iterator reference print_r($flat); # your tree
$flat
现在包含$flat
所有值 – 但是重新sorting。 演示 。
你确定输出数组是正确的吗? 当然,关键2
应该是1的孩子(因为2
有'parent'=>1
)? 如果情况并非如此,我不明白究竟在做什么以及这些键是如何相互关联的。
如果2
应该是1的孩子,这是有效的:
$keep = array(); foreach ($a as $k => &$v) { // Loop the array first time and create references to // structure the array how you want it if ($v['parent']) { $a[$v['parent']][0] = array($k => &$v); } else $keep[] = $k; } foreach ($a as $k => $v) { // Loop it again to get rid of non-root nodes from the root if (!in_array($k,$keep)) { unset($a[$k]); } } print_r($a);