【问题标题】:How to efficiently build a tree from a flat structure in php?如何有效地从 php 中的平面结构构建树?
【发布时间】:2011-07-11 06:35:10
【问题描述】:

数组数据结构:

 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
)
 .....

【问题讨论】:

  • 为什么你不在这里使用“foreach” for($i=0;$i
  • ooo...因为使用foreach,我不知道如何取消设置...我只是一个初学者..:)
  • @bingjie2680,你可以使用foreach($arr as $key=>$val)然后unset($arr[$key])
  • 它似乎可以消除错误。但整个函数返回相同的根,没有孩子
  • 问题出在您的$children 数组中。我猜它是空的。

标签: php algorithm recursion tree


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你能把var_dump($children)发在这里吗?
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2013-01-22
      相关资源
      最近更新 更多