Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7599395
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T22:39:02+00:00 2026-05-30T22:39:02+00:00

I’m trying to display this kind of array: $nodes = array( 1 => array(

  • 0

I’m trying to display this kind of array:

$nodes = array(

  1 => array(
         'title'    => 'NodeLvl1',
         'children' => array(),
       ),    
  2 => array(
         'title'    => 'NodeLvl1',
         'children' => array(        
                         1 => array(
                                'title'    => 'NodeLvl2',
                                'children' => array(),
                             ),    
                         2 => array(
                                'title'    => 'NodeLvl2',
                                'children' => array(


                                   1 => array(
                                          'title'    => 'NodeLvl3',
                                          'children' => array(),
                                       ),


                                   2 => array(
                                          'title'    => 'NodeLvl3',
                                          'children' => array(),
                                       ),    
                                ),
                              ),    

                       ),
       ),

  3 => array(
         'title'    => 'NodeLvl1',
         'children' => array(),
       ),    
);

like this:

<ul>
  <li>
    NodeLvl1
  </li>
  <li>
    NodeLvl1
      <ul>
        <li>NodeLv2</li>
         ...

      </ul>
  </li>
  ...

Basically a nested list taking into account the “children” property. So far I’ve come up with this:

class It extends RecursiveIteratorIterator{

  protected
    $tab    = "\t";

  public function beginChildren(){

    if(count($this->getInnerIterator()) == 0)
      return;

    echo str_repeat($this->tab, $this->getDepth())."<ul>\n";
  }

  public function endChildren(){


    if(count($this->getInnerIterator()) == 0)
      return;

    echo str_repeat($this->tab, $this->getDepth())."\n</ul>";
  }

  public function nextElement(){
    echo str_repeat($this->tab, $this->getDepth() + 1).'<li>';
  }

}

$it = new It(new RecursiveArrayIterator($nodes));

foreach($it as $key => $item)
  echo $item;

Which doesn’t work quite right: I get each item wrapped between <ul>s and I don’t know how can I close <li>s…

Any ideas on how to make this work? Also is it possible to get all the array properties (the actual element), instead of just the “title” property inside my foreach() loop? And can this be done with objects instead of arrays?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T22:39:03+00:00Added an answer on May 30, 2026 at 10:39 pm

    You can use RecursiveCachingIterator to do what you want. Here is an example, (source: https://github.com/cballou/PHP-SPL-Iterator-Interface-Examples/blob/master/recursive-caching-iterator.php)

    <?php
    // example navigation array
    $nav = array(
        'Home' => '/home',
        'Fake' => array(
            'Double Fake' => array(
                'Nested Double Fake' => '/fake/double/nested',
                'Doubly Nested Double Fake' => '/fake/double/doubly'
            ),
            'Triple Fake' => '/fake/tripe'
        ),
        'Products' => array(
            'Product 1' => '/products/1',
            'Product 2' => '/products/2',
            'Product 3' => '/products/3',
            'Nested Product' => array(
                'Nested 1' => '/products/nested/1',
                'Nested 2' => '/products/nested/2'
            )
        ),
        'Company' => '/company',
        'Privacy Policy' => '/privacy-policy'
    );
    
    class NavBuilder extends RecursiveIteratorIterator {
    
        // stores the previous depth
        private $_depth = 0;
    
        // stores the current iteration's depth
        private $_curDepth = 0;
    
        // store the iterator
        protected $_it;
    
        /**
         * Constructor.
         *
         * @access  public
         * @param   Traversable $it
         * @param   int         $mode
         * @param   int         $flags
         */
        public function __construct(Traversable $it, $mode = RecursiveIteratorIterator::SELF_FIRST, $flags = 0)
        {
            parent::__construct($it, $mode, $flags);
    
            // store the caching iterator
            $this->_it = $it;
        }
    
        /**
         * Override the return values.
         *
         * @access  public
         */
        public function current()
        {
            // the return output string
            $output = '';
    
            // set the current depth
            $this->_curDepth = parent::getDepth();
    
            // store the difference in depths
            $diff = abs($this->_curDepth - $this->_depth);
    
            // get the name and url of the nav item
            $name = parent::key();
            $url = parent::current();
    
            // close previous nested levels
            if ($this->_curDepth < $this->_depth) {
                $output .= str_repeat('</ul></li>', $diff);
            }
    
            // check if we have the last nav item
            if ($this->hasNext()) {
                $output .= '<li><a href="' . $url . '">' . $name . '</a>';
            } else {
                $output .= '<li class="last"><a href="' . $url . '">' . $name . '</a>';
            }
    
            // either add a subnav or close the list item
            if ($this->hasChildren()) {
                $output .= '<ul>';
            } else {
                $output .= '</li>';
            }
    
            // cache the depth
            $this->_depth = $this->_curDepth;
    
            // return the output ( we could've also overridden current())
            return $output;
        }
    
    }
    ?>
    

    Usage

    <?php
    
    try {
    
        // generate the recursive caching iterator
        $it = new RecursiveCachingIterator(new RecursiveArrayIterator($nav));
    
        // build the navigation with the iterator
        $it = new NavBuilder($it, RecursiveIteratorIterator::SELF_FIRST);
    
        // display the resulting navigation
        echo '<ul id="nav">' . PHP_EOL;
        foreach ($it as $value) {
            echo $value . "\n";
        }
        echo '</ul>' . PHP_EOL;
    
    } catch (Exception $e) {
        var_dump($e); die;
    }
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to render a haml file in a javascript response like so:
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.