I'm looking to write a function that takes an array of pages/categories (from a flat database result) and echo to a nested page/category <ul>
(HTML unordered list) items based on the parent ids. I would like to do this recursively, so that any level of nesting can be done.
+-------+---------------+---------------------------+
| id | parent_id | title |
+-------+---------------+---------------------------+
| 1 | 0 | Parent Page |
| 2 | 1 | Sub Page |
| 3 | 2 | Sub Sub Page |
| 4 | 0 | Another Parent Page |
+-------+---------------+---------------------------+
And this is the array I would like to end up with to process in my view files:
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
[title] => Parent Page
[children] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 1
[title] => Sub Page
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 1
[title] => Sub Sub Page
)
)
)
)
)
[1] => Array
(
[id] => 4
[parent_id] => 0
[title] => Another Parent Page
)
)
I found this article which is SIMILAR but NOT DUPLICATE to the one I'm posting, which is where I found the below function which could help with the answer.
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;
}
$tree = buildTree($rows);
EDIT:
I want to echo the data in the below structure:
<ul>
<li><a href="#">Parent Page</a>
<ul>
<li><a href="#">Sub Page</a>
<ul>
<li><a href="#">Sub Sub Page</a>
</ul>
</li>
</ul>
</li>
<li><a href="#">Another Parent Page</a>
</li>
</ul>