【发布时间】: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