I am developing a content management system and I have run into an issue with child-parent relationships of items in the CMS.
Basically I have a system that can create pages and when a page is created you can select a parent page for sub-navigation. This is all fine and dandy until I try to generate the navigation from the DB.
I’m not sure if some sort of join would be better but I prefer to get all the data in an array and manipulate the array with php.
My array of results from the DB is like this:
Array
(
[0] => Array
(
[id] => 27
[name] => home
[link] => home.html
[parent] => 0
)
[1] => Array
(
[id] => 30
[name] => about
[link] => about.html
[parent] => 27
)
)
I need to loop through an array like this that can have any number of navigation and intelligently sort it into its parent child relationships. I was able to do it but only one level deep. It needs to manage children with children with children etc. with an infinite number of layers and output it to HTML unordered nested lists.
<ul>
<li>
<a>Nav</a>
<ul>
<li>
<a>Subnav</a>
<ul>
<li>
<a>Sub Sub nav</a>
</li>
</ul>
</li>
</ul>
<li>
<ul>
Etc. …
I don’t think you should get into objects. Plus I think it would just be extra work to generate objects and etc. In my opinion you should loop through the array and generate a multidimensional array that represents the navigational hierarchy and then loop the generated array recursively to generate your HTML. I’ve done a sample code for you, it works the way you want it to but you probably want to make some changes.
functions
** sample usage **
You can probably do both things in one step but I think it’s neater to generate the multidimensional array first. Goodluck!