我有一个类别数组,其中id是类别的id,parent表示类别的父ID(id 0表示最顶层的父节点),value是数组的标题。该路径最初设置为类别的ID。数组如下:
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
[value] => Corporate Files
[path] => 1
)
[1] => Array
(
[id] => 2
[parent] => 0
[value] => Products Files
[path] => 2
)
[2] => Array
(
[id] => 3
[parent] => 1
[value] => Communications Materials
[path] => 3
)
[3] => Array
(
[id] => 4
[parent] => 1
[value] => Group Technical
[path] => 4
)
[4] => Array
(
[id] => 5
[parent] => 1
[value] => New Projects
[path] => 5
)
[5] => Array
(
[id] => 6
[parent] => 2
[value] => Product Range
[path] => 6
)
[6] => Array
(
[id] => 7
[parent] => 2
[value] => WL4
[path] => 7
)
);
我想在数组中生成类别的路径。所以输出应该是
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
[value] => Corporate Files
[path] => 1
)
[1] => Array
(
[id] => 2
[parent] => 0
[value] => Products Files
[path] => 2
)
[2] => Array
(
[id] => 3
[parent] => 1
[value] => Communications Materials
[path] => 1,3
)
[3] => Array
(
[id] => 4
[parent] => 1
[value] => Group Technical
[path] => 1,4
)
[4] => Array
(
[id] => 5
[parent] => 1
[value] => New Projects
[path] => 1,5
)
[5] => Array
(
[id] => 6
[parent] => 2
[value] => Product Range
[path] => 2,6
)
[6] => Array
(
[id] => 7
[parent] => 2
[value] => WL4
[path] => 2,7
)
);
我写了以下功能。
function findparent($id,$path){
global $categories;
global $catcnt;
if($id==0){
echo $path."<br />"; //this outputs path currently
return $path;
}
for($i=0;$i<$catcnt;$i++){
if($id==$categories[$i]['id']){
$path=$id.",".$path;
findparent($categories[$i]['parent'],$path);
}
}
}
for($i=0;$i<count($categories);$i++){
$categories[$i]['path']=(string)findparent($categories[$i]['parent'],$categories[$i]['id']); //this doesnt assign it currectly
}
,输出为:
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
[value] => Corporate Files
[path] =>
)
[1] => Array
(
[id] => 2
[parent] => 0
[value] => Products Files
[path] =>
)
[2] => Array
(
[id] => 3
[parent] => 1
[value] => Communications Materials
[path] =>
)
[3] => Array
(
[id] => 4
[parent] => 1
[value] => Group Technical
[path] =>
)
[4] => Array
(
[id] => 5
[parent] => 1
[value] => New Projects
[path] =>
)
[5] => Array
(
[id] => 6
[parent] => 2
[value] => Product Range
[path] =>
)
[6] => Array
(
[id] => 7
[parent] => 2
[value] => WL4
[path] =>
)
);
我哪里错了?
答案 0 :(得分:2)
findparent
仅在id
为零时才会返回。
在递归findparent
调用之前,您需要第二个return语句。
答案 1 :(得分:1)
由于您不需要处理多个级别,因此您可以通过一个简单的foreach
直接使用数组本身来完成它自身的功能。
foreach ($array as &$node)
{
if ($node['parent'])
{
$node['path'] = $node['parent'] . ',' . $node['path'];
}
}
unset($node);
但是,您可以将其置于其自身的功能中,但就我所见,您不需要任何全局变量。
你在这里看到的是简单的字符串连接,这就像你想要的那样创建数组。我的第一个评论更多的是用n深度而不是1深度来管理结构。 Demo