将 PHP 数组平整到层次结构树
我有一个包含以下键的数组
id
parent_id
name
示例数组:
array(7) {
[0]=>
array(3) {
["id"]=>
string(1) "4"
["parent_id"]=>
string(1) "0"
["name"]=>
string(16) "Top Level Page 4"
}
[1]=>
array(3) {
["id"]=>
string(1) "5"
["parent_id"]=>
string(1) "1"
["name"]=>
string(19) "Second Level Page 1"
}
[2]=>
array(3) {
["id"]=>
string(1) "6"
["parent_id"]=>
string(1) "2"
["name"]=>
string(19) "Second Level Page 2"
}
[3]=>
array(3) {
["id"]=>
string(1) "7"
["parent_id"]=>
string(1) "5"
["name"]=>
string(18) "Third Level Page 1"
}
[4]=>
array(3) {
["id"]=>
string(1) "3"
["parent_id"]=>
string(1) "0"
["name"]=>
string(16) "Top Level Page 3"
}
[5]=>
array(3) {
["id"]=>
string(1) "2"
["parent_id"]=>
string(1) "0"
["name"]=>
string(16) "Top Level Page 2"
}
[6]=>
array(3) {
["id"]=>
string(1) "1"
["parent_id"]=>
string(1) "0"
["name"]=>
string(16) "Top Level Page 1"
}
}
我想做的是使用此数组显示层次结构树,我目前拥有的代码正在生成:
Top Level Page 4
--Second Level Page 1
---Second Level Page 2
----Third Level Page 1
Top Level Page 3
Top Level Page 2
Top Level Page 1
理想情况下,我需要产生以下结果,但具有无限的级别:
Top Level Page 4
-Second Level Page 1
-Second Level Page 2
--Third Level Page 1
Top Level Page 3
Top Level Page 2
Top Level Page 1
到目前为止,我的代码是:
$level = 1;
foreach ($data as $row) {
if ($row['parent_id'] == 0) {
echo $row['name'] . '<br/>';
} else {
$level++;
foreach ($data as $m) {
if ($m['parent_id'] === $row['parent_id']) {
$c = 0;
$append = '';
while ($c < $level) {
$append.="-";
$c++;
}
echo $append . $row['name'] . '<br/>';
}
}
}
}
}
如果有人能给我一些关于如何实现这一目标的指示,那将不胜感激。
我在这里找到了一个解决方案:从PHP数组为下拉选择字段创建嵌套列表