Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将平面结构排序到只知道父级的树中_Php_Algorithm_Tree - Fatal编程技术网

Php 将平面结构排序到只知道父级的树中

Php 将平面结构排序到只知道父级的树中,php,algorithm,tree,Php,Algorithm,Tree,给定以下阵列结构: array( 55 => array( 'ident' => 'test 1', 'depth' => 1, ), 77 => array( 'parent_id' => 55, 'ident' => 'test 2', 'depth' => 2, ) ); 是否有一种通用算法可以用来将其转换为嵌套树 i、 e 我提供的示例是简化的,实际案

给定以下阵列结构:

array(
   55 => array(
       'ident' => 'test 1',
       'depth' => 1,
   ),
   77 => array(
       'parent_id' => 55,
       'ident' => 'test 2',
       'depth' => 2,
   )
);
是否有一种通用算法可以用来将其转换为嵌套树

i、 e


我提供的示例是简化的,实际案例包括数百个节点+深度高达15个。

使用引用帮助很大。这样,即使已插入子对象,也可以将其附加到子对象

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

这方面的一些演示:

您尝试了什么?我会以此为出发点:网站上有很多这样的问题,试着寻找“php构造层次结构”或类似的东西,例如:@SergiuParaschiv只是为了注意;你链接到的东西有一个可怕的复杂性(至少当它在O(n)=>中也可行时,请参见下面的答案),我认为你必须首先尝试它,以了解这个问题的存在,你不认为吗?递归解决方案对于“数百个节点”来说是完全可以接受的。@SergiuParaschiv递归地实际上是
O(n^2)
Imagine 700个节点……递归地“仅”±250k次迭代(平均)[加上函数调用通常也相对较慢]或者foreach总共只有700次迭代,并且有引用……我认为在这一点上,它开始产生显著的不同。我可能是唯一一个更愿意避免像瘟疫一样的PHP引用的人。。永远不会少,有趣的答案。@Mackie地狱,参考文献是可怕的。没有它们,一半的递归内容将是不可能的;我也会尽量避免它们,但这实际上是一个非常有效的用例。因为我无法想象其他的解决方案会在O(n)中运行,并且不使用引用…@mackiee:我认为大多数人讨厌PHP中的引用,这可能会导致一团混乱。但是bwoebi在性能方面是正确的,没有它们,内存或处理时间都会飞涨,必须存储路径等等。有趣的是,今晚我将与它们一起玩=]谢谢,见解深刻!我想这是一个事实,我觉得PHP中的大多数引用在幕后感觉非常好,最初阅读它似乎没有直接点击-除了答案和演示上的+1!
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]);
    }
}