我正在使用此处找到的buildTree函数来获取父级的所有子级,但是我正在努力调整代码以生成遍及树的所有可能分支。
样本数据:
Array
(
[0] => Array
(
[id] => 7
[parent_id] => 6
)
[1] => Array
(
[id] => 8
[parent_id] => 6
)
[2] => Array
(
[id] => 17
[parent_id] => 7
)
[3] => Array
(
[id] => 18
[parent_id] => 7
)
[4] => Array
(
[id] => 20
[parent_id] => 17
)
[5] => Array
(
[id] => 21
[parent_id] => 17
)
[6] => Array
(
[id] => 22
[parent_id] => 17
)
)
buildTree:
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
}
我要输出的内容:
Array
(
[0] => Array
(
6, 7, 17, 20
)
[1] => Array
(
6, 7, 17, 21
)
[2] => Array
(
6, 7, 17, 22
)
[3] => Array
(
6, 7, 18
)
[4] => Array
(
6, 8
)
)
我尝试使用foreach循环而不是if($children)
来生成结果数组中的下一个键,并从树的更高位置合并现有数据,但是没有成功。
非常感谢您的帮助!
答案 0 :(得分:0)
好吧,在buildTree函数中有几个错误。首先,您无法检查数组中不存在的键,例如“ parent”(存在“ parent_id”)。
请检查这是否是您想要的:
<?php
$input =
[
[
"id" => 7,
"parent_id" => 6
],
[
"id" => 8,
"parent_id" => 6
],
[
"id" => 17,
"parent_id" => 7
],
[
"id" => 18,
"parent_id" => 7
],
[
"id" => 20,
"parent_id" => 17
],
[
"id" => 21,
"parent_id" => 17
],
[
"id" => 22,
"parent_id" => 17
]
];
function buildTree(array $elements, $parentId = 0)
{
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if (!empty($children)) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
print_r(buildTree($input, 7));