2

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>
2

1 Answer 1

1

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();
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.