我有这个数组:
$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中的变量引用/别名是如何工作的。
看下面的示例代码,它看起来和你的代码没有太大的不同,但是使用引用来访问任何父节点,即使它已经"移动"了:
# 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
中的所有值-但重新排序。演示。
您确定输出数组是正确的吗?当然,关键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);