[英]Recursion in php, hierarchical structure in array, print tree
i have a tree array like this with parent->child structure: 我有一个像这样的树形数组,带有parent-> child结构:
Array
(
[0] => Array
(
[id] => 12
[address] => root addr
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 11
[address] => child addr
[parent_id] => 12
[children] => Array
(
[0] => Array
(
[id] => 16
[address] => child addr 2
[parent_id] => 11
[children] => Array
(
[0] => Array
(
[id] => 19
[address] => child addr 3
[parent_id] => 16
)
)
)
[1] => Array
(
[id] => 18
[address] => child addr 4
[parent_id] => 11
)
[2] => Array
(
[id] => 20
[address] => child addr 5
[parent_id] => 11
)
)
)
)
)
[1] => Array
(
[id] => 17
[address] => root addr 2
[parent_id] => 0
)
)
i have a build tree function, that print my tree structure : 我有一个构建树函数,可以打印我的树结构:
function printTree($data, $level = 0, $p_counter = 1) {
foreach ($data as $item) {
if ($item['parent_id'] == 0) {
$addr = $p_counter . '. ' . $item['address'];
$p_counter++;
}
else if ($item['parent_id'] != 0) {
$addr = str_repeat(' - ', $level) . $item['address'];
} else {
$addr = $item['address'];
}
global $result;
$result['aaData'][] = Array(
$addr,
);
if (isset($item['children'])) {
printTree($item['children'], $level + 1, $p_counter + 1);
}
}
return $result;
}
Now my output is like this with childs levels 现在我的输出是这样的,带有儿童水平
1. root addr
- child addr
- - child arr 2
- - - child arr 3
- - child addr 4
- - child addr 5
2. root addr 2
my goal is to print array like this, need help! 我的目标是打印这样的数组,需要帮助!
1. root addr
1-1. child addr
1-1-1. child arr 2
1-1-1-1. child arr 3
1-1-2. child addr 4
1-1-3. child addr 5
2. root addr 2
If you use 如果您使用
foreach ($data as $key => $item) {
}
You could use $key to get the 0's, 1's and 2's in your string. 您可以使用$ key在字符串中获取0、1和2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.