Question

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>
Was it helpful?

Solution

That is normally a three step procedure:

  1. You implement a concrete RecursiveIterator that offers recursion iteration for your tree structure. It looks like that RecursiveArrayIterator is suiting your needs here.
  2. You iterate over it with a RecursiveIteratorIterator that is able to turn the recusion into your output (compare with RecursiveTreeIterator).
  3. You do the output by iterating with foreach over your more concrete RecursiveIteratorIterator.

Code Example:

   // consume implementation of step 1
   $it = new PagesRecursiveIterator($pages);

   // consume implementation of step 2
   $list = new RecursiveUlLiIterator($it);

   // perform iteration given in step 3
   foreach($list as $page) {
       echo $page->getName();
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top