Search code examples
phpmysqlmenusubmenu

How can I make a submenu


I have the next database:

enter image description here

I have the below function:

<?php 

$connection = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("database1", $connection) or die(mysql_error());

function loop_array($array = array(), $parent_id = 0)

{
  if (!empty($array[$parent_id])) {
      echo '<ul>';
      foreach ($array[$parent_id] as $items) {
          echo '<li>';
          echo '<a href="?page='.$items['id'].'">'.$items['title'].'</a>';
          loop_array($array, $items['id']);
          echo '</li>';
      }
  }
}

function displays_menus_revised()

{
  $sql = "SELECT * FROM pages";
  $query = mysql_query($sql) or die(mysql_error());
  $array = array();
  if (mysql_num_rows($query)) {
    while ($rows = mysql_fetch_array($query)) {
      $array[$rows['parent_id']][] = $rows;
    }
    loop_array($array);
  }
}

 ?>

My problem is the funtion show the records like in the left picture. I want the function to show the records like in the right picture. Can you tell me where is the problem? What i must change that the function show records like in the right picture? Thanks.

enter image description here


Solution

  • So nice code, with such a small slip. Only the closing 'ul' is missing.

    function loop_array($array = array(), $parent_id = 0)
    {
      if (!empty($array[$parent_id])) {
          echo '<ul>';
          foreach ($array[$parent_id] as $items) {
              echo '<li>';
              echo '<a href="?page='.$items['id'].'">'.$items['title'].'</a>';
              loop_array($array, $items['id']);
              echo '</li>';
          }
          echo '</ul>';
      }
    }