将扁平结构整理成树只知道父母

时间:2013-10-11 15:22:35

标签: php algorithm tree

给定以下数组结构:

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个深度。

1 个答案:

答案 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]);
    }
}

一些演示:http://3v4l.org/D6l6U#v500

相关问题