I have a data set stored in an array that references itself with parent-child ids:
id
, parent_id
, title
etc. The top tier has a parent_id
of 0
, and there can be countless parent-child relationships.
So I'm sorting through this array with a foreach
loop within a recursive function to check each array element against its parent element, and I think I've been staring at this method too long.
I do end up with the elements in the correct order, but I can't seem to get my lists nested correctly, which makes me think that the method doesn't really work.
- Is this the best route to take?
- What can I do to improve and fix this method
- Is there another trick that I can apply?
Here is my source:
<div>
<div>Subpages</div>
<ul>
<?php subPages($this->subpages->toArray(), 0) ?>
</ul>
<br>
<a href="javascript:;" onclick="">Add New Subpage</a>
</div>
<?php
function subPages($subpages, $parent){
foreach($subpages as $key => &$page){
$newParent = $page['id'];
//If the current page is the parrent start a new list
if($page['id'] == $parent)
{
//Echo out a new list
echo '<ul>';
echo '<li class="collapsed">';
echo '<a href="javascript:;" class="toggle">+</a>';
echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';
subPages($subpages, $newParent);
echo '</li>';
echo '</ul>';
}
//If the page's parent id matches the parent provided
else if($page['parent_id'] == $parent)
{
//Echo out the link
echo '<li class="collapsed">';
echo '<a href="javascript:;" class="toggle">+</a>';
echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';
//Set the page as the new parent
$newParent = $page['id'];
//Remove page from array
unset($subpages[$key]);
//Check the rest of the array for children
subPages($subpages, $newParent);
echo '</li>';
}
}
}
?>
As always, any assistance is appreciated. Please let me know if something isn't clear.