我有一个像这样的树形数组,带有parent->子结构:
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
)
)
我有一个构建树函数,它打印我的树结构:
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;
}
现在我的输出与子级别
相似1. root addr
- child addr
- - child arr 2
- - - child arr 3
- - child addr 4
- - child addr 5
2. root addr 2
我的目标是打印这样的数组,需要帮助!
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
答案 0 :(得分:0)
如果您使用
foreach ($data as $key => $item) {
}
您可以使用$ key获取字符串中的0,1和2。