Creating nested foreach

hey folks,
i m building a menu which has unordered list inside unordered and it goes on. i can comprehend making a for each array for just unordered and listed items but how do i carry nested ul inside ul? i m new at php so its hard for me to imagine how to make it. can i get some help. e.g


<ul>
<li>Home</li>
<li>About me</li>
<ul class="subchild">
<li>About myself</li>
<li>About My folio</li>
<li>My projects</li>
<li>My Services</li>
</ul>
</ul>

now this is a vague example. of course i got tons more links. so how do i nest them :confused:

Try explaining what part you’re finding hard to understand, you’ll get a lot more support if you show a little effort in trying to figure it out. :wink:

Loops, echo’ing, arrays, recursion ?

well i m a new bie and for me both of methods are hard to get my head around

The example logic_earth gave is called a recursive function, which basically is coded in such a way that it can call itself and not get caught in an infinite loop, it’s an elegant (usually) solution to any problem where you’re dealing with n tier hierarchy.

As far as nesting foreach loops, it’s basically like this.


	echo '<ul>';
	foreach ($list as $key=>$val)
	{
		if (is_array($val)) {
			echo '<ul>';
			foreach ($val as $k=>$k)
			{
				echo '<li>$k</li>';
			}
			echo '</ul>';
		} else {
			echo "<li>$val</li>";	
		}
	}
	echo '</ul>';

Note the $val is reused in the inner foreach, because this is an array that holds the sub array.

You can go on forever, however for anything deeper than 2, the code is going to look too ugly and you should consider a function (pref. a recursive one).

i didn’t got where u used the nested listed items. all went from above the head

Rough implementation:


$links = array(
  'one',
  'two',
  'three' => array(
    'one',
    'two',
    'three' => array(
      'one',
      'two',
      'three',
      'four',
      'five'
    ),
    'four',
    'five'
  ),
  'four',
  'five'
);

function nestedList ( array $list )
{
  $r = '<ul>';

  foreach ( $list as $key => $value ) {
    if ( is_array( $value ) ) {
      $r .= '<li>' . $key . nestedList( $value ) . '</li>';
      continue;
    }

    $r .= "<li>{$value}</li>";
  }

  return $r . '</ul>';
}

var_dump( nestedList( $links ) );

And the output: (Formatted of course)


<ul>
  <li>one</li>
  <li>two</li>
  <li>three
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three
        <ul>
          <li>one</li>
          <li>two</li>
          <li>three</li>
          <li>four</li>
          <li>five</li>
        </ul>
      </li>
      <li>four</li>
      <li>five</li>
    </ul>
  </li>
  <li>four</li>
  <li>five</li>
</ul>

looping i m just not very hands on with,
echoing is something easy
array is easy too
recursion is a new thing for me
still i fail to understand how is nested ul is assigned a different class than the outer ul. my concepts for php is very week as still i m a very new at this