给定以下数组结构:
array(
55 => array(
'ident' => 'test 1',
'depth' => 1,
),
77 => array(
'parent_id' => 55,
'ident' => 'test 2',
'depth' => 2,
)
);
是否有可用于将其转换为嵌套树的通用算法?
即
array(
55 => array(
'ident' => 'test 1',
'depth' => 1,
'children' => array(
77 => array(
'parent_id' => 55,
'ident' => 'test 2',
'depth' => 2,
)
)
)
);
我提供的示例是简化的,真实案例包括数百个节点+最多15个深度。
答案 0 :(得分:4)
使用引用有很多帮助。这样,即使已经插入了孩子,您仍然可以附加到孩子身上。
foreach ($array as $key => &$sub) {
if (isset($sub['parent_id'])) {
$array[$sub['parent_id']]['children'][$key] = &$sub;
}
}
unset($sub); // unset the reference to make sure to not overwrite it later...
// now remove the entries with parents
foreach ($array as $key => $sub) {
if (isset($sub['parent_id'])) {
unset($array[$key]);
}
}