繁体   English   中英

如何有效地从 php 中的平面结构构建树?

[英]How to efficiently build a tree from a flat structure in php?

数组数据结构:

 id   name    parent_id   children

现在我有一个根数组和一组子数组,我想构建一个树结构,这就是我所拥有的:

更新::

function buildTree($root,$children)
{   
    foreach($children as $key=>$val){
        print_r($val);
        $val['children']=array();
        if($val['parent_id']==$root['id']){
            $root['children'][]=$val;
            //remove it so we don't need to go through again
            unset($children[$key]);
        }
    }
    if(count($root['children'])==0)return;
    foreach($root['children'] as $child){
        $this->buildTree($child,$children);
    }
}

这将返回相同的根,而不是添加的子项,任何人都可以帮助我。 多谢。

更新: print_r($val) 打印出来:

 Array
(
[id] => 3
[name] => parent directory2
[type] => d
[creat_time] => 2011-07-08 06:38:36
[parent_id] => 1
[user_id] => 1
)
Array
(
[id] => 5
[name] => parent directory3
[type] => d
[creat_time] => 2011-07-08 06:38:36
[parent_id] => 1
[user_id] => 1
)
 .....

尝试更改您的 function 以通过引用获取参数,如下所示:

function buildTree(&$root,&$children) {

否则,您将在每次调用中获得根/子 arrays 的新副本,因此您将永远无法获得整棵树。

您可以在手册中找到更多信息: http://www.php.net/manual/en/language.references.pass.php

看起来您的 $children 数组以 1 开头,但您的“for”以 0 开头

如果效率是您所要求的,您可能需要考虑使用引用而不是递归,如下所述: https://stackoverflow.com/a/34087813/2435335

这将执行时间减少到不到一秒

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM