I’m having trouble getting my head around RecrusiveIteratorIterator and relatives to iterate over an multi-dimensional array of pages to build a multi-level menu in PHP.
Normally I just create a function that loops over a level, and calls itself to loop over any children. But I’m wanting to utilise the iterator interfaces in PHP to make my code better.
My array looks like this:
$pages = array(
new Page(1, 'Home'),
new Page(2, 'Pages', array(
new Page(3, 'About'),
new Page(4, 'Contact')
)),
new Page(5, 'Categories', array(
new Page(6, 'Clothing'),
new Page(7, 'DVDs')
))
);
The arguments in my Page constructor are simply the page ID and page name.
How can I use PHP’s iterators to build a menu that looks like this?
<ul>
<li>Home</li>
<li>Pages
<ul>
<li>About</li>
<li>Contact</li>
</ul>
</li>
<li>Categories
<ul>
<li>Clothing</li>
<li>DVDs</li>
</ul>
</li>
</ul>
That is normally a three step procedure:
RecursiveIteratorthat offers recursion iteration for your tree structure. It looks like thatRecursiveArrayIteratoris suiting your needs here.RecursiveIteratorIteratorthat is able to turn the recusion into your output (compare withRecursiveTreeIterator).foreachover your more concreteRecursiveIteratorIterator.Code Example: