我有一个构建树数组的函数。例:
Array
(
[0] => Array
(
[id] => 12
[address] => 'Ukraine'
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 11
[address] => Crimea
[parent_id] => 12
[children] => Array
(
[0] => Array
(
[id] => 16
[address] => Yalta
[parent_id] => 11
)
)
)
)
)
我有打印树的功能(我想获得缩进级别的输出):
function printTree($data) {
foreach ($data as $item) {
if ($item['parent_id'] != 0)
echo ' - ' . $item['address'] . "<br>";
else
echo $item['address'] . "<br>";
if (isset($item['children'])) {
printTree($item['children']);
}
}
}
但我的结果只有一个级别,因为我的if
不正确:
Ukraine
- Crimea
- Yalta
我需要使用所有级别的缩进。我需要在if
报表中更改哪些内容?
Ukraine
- Crimea
- Yalta
这样重写代码:
function printTree($data, $level = 0) {
foreach ($data as $item) {
if ($item['parent_id'] != 0) {
/* here we corrects indent: */
echo str_repeat(' ', $level) . ' - ' . $item['address'] . "<br>";
} else {
echo $item['address'] . "<br>";
}
if (isset($item['children'])) {
printTree($item['children'], $level + 1);
}
}
}
您只需添加一个深度变量来控制要在每个子项之前添加多少空白:
<?php
$data = array(
0 => array(
'id' => 12,
'address' => 'Ukraine',
'parent_id' => 0,
'children' => array(
0 => array(
'id' => 11,
'address' => Crimea,
'parent_id' => 12,
'children' => array(
0 => array(
'id' => 16,
'address' => Yalta,
'parent_id' => 11,
)
)
)
)
)
);
printTree($data);
function printTree($data, $depth = 0) {
foreach ($data as $item) {
if ($item['parent_id'] != 0)
echo str_repeat(' ', $depth), "- {$item['address']}'n";
else
echo "{$item['address']}'n";
if (isset($item['children'])) {
printTree($item['children'], ++$depth);
}
}
}
输出:
Ukraine
- Crimea
- Yalta