hierarchical structure in array, recursion in php
542
i have hierarchical structure in array like this:
item root 1
- item child 1
-- item child 2
item root 2
- item child
i want to get:
1. item root 1
1-1. item child 1
1-1-1. item child 2
2. item root 2
2-1. item child
My function to build tree
function printTree($data, $level = 0, $counter = 1) {
foreach ($data as $item) {
if ($item['parent_id'] == 0) {
$addr = $counter . '. ' . $item['address'];
$counter++;
}
else if ($item['parent_id'] != 0) {
$addr = $counter . '-' . $counter . ' ' . $item['address'];
} else {
$addr = $item['address'];
}
global $result;
$result['aaData'][] = Array(
$addr,
$item['mask'],
$item['status'],
$item['subnets'],
$item['therange'] = $item['start'] . ' - ' . $item['end'],
$item['type'],
$item['node'],
$item['id'],
);
if (isset($item['children'])) {
printTree($item['children'], $level + 1, $counter + 1);
}
}
return $result;
}
But my result is incorrect, root's element count normal, but childs wrong, how can i fix this? need help, thanks!
Answer
Solution:
Here is some code, with your specific test case:
EDIT (corrected with $counter, not id)
This is just a basic recursive function that performs a very similar task. It is not the full solution. Put your specific logic in there to create the final output you need, but the basic 'counter' idea you ask for works.
Hope this helps.