如何在php中高效构建树形结构?

3

数组数据结构:

 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,我不知道如何取消设置(unset)...我只是一个初学者..:) - bingjie2680
@bingjie2680,你可以使用foreach($arr as $key=>$val)然后unset($arr[$key]) - k102
似乎可以轻松解决这个错误。但整个函数返回相同的根,没有子节点。 - bingjie2680
问题出在你的 $children 数组上。我猜它是空的。 - k102
你是否已经将所有的项目存储到数组或其他地方?我可以帮你设计一个线性时间算法 ;) - Kowser
显示剩余3条评论
3个回答

2
尝试将您的函数更改为按引用传递参数,如下所示:
function buildTree(&$root,&$children) {

否则,每次调用都会得到根/子数组的新副本,因此您永远无法获取整个树。您可以在手册中找到更多信息:http://www.php.net/manual/en/language.references.pass.php

0

看起来你的$children数组从1开始,但你的“for”从0开始


你能否使用 var_dump($children) 并在此处发布它? - k102

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接