简体   繁体   中英

PHP - Drop down not showing all items in mysql

I am Trying to make a drop down menu, and list multiple items as well.

like for example: here is my database: 在此处输入图片说明

if you see in that image you can see only one of the rows have a parent if i want multiple rows to have a parent of 'Far Far Away123' it only shows one of the items

<?php

  function build_dropdown ($parent, $pages){
  $items = "";
    foreach($pages as $page){
    // $items = "";
  if($page['parent'] == $parent){
    $items = $page;
  } // END if
    } // END foreach

    if(is_array($items)){ // If a sub 
      echo '<ul id="sub_menu" class="sub_navagation'. $items['id'] .'">';
        echo '<li>'.$items['page_name'].'</li>';
      echo '</ul>'; 
    } // END if 
  }// End Function

  $sql = "SELECT * FROM pages ORDER by item_order";
  $result = mysqli_query($db, $sql);
  confirm_query($result);

  while ($row = mysqli_fetch_assoc($result)) {
    $pages[] = $row; // Add each row to $pages array to use later
  }


  foreach($pages as $key => $page){

    if($page['parent'] == 'none'){ ?>

      <li id = "<?php echo $page['id']; ?>">
        <a href="page.php?id=<?php echo $page['id']; ?>" title="<?php echo     $page['page_title']; ?>">
          <?php echo $page['page_name']; ?>
        </a>
        <?php  ?>


<?php 
    } // END if
    build_dropdown($page['page_name'], $pages); // If there are child items     then build them out
echo "</li> ";
  } // END foreach
?>

Thanks

It is because you add only one.

You have a foreach searching all pages for subitems and remember only one of them for the latter if (is_array())

function build_dropdown($parent, $pages)
{
    // item is an array
    $items = array();
    foreach($pages as $page) {
        if ($page['parent'] == $parent) {
            // add an element to the array
            $items[] = $page;
        } // END if
    } // END foreach
    if ($items) {
        echo '<ul id="sub_menu" class="sub_navagation">';
        foreach ($items as $item) {
            echo '<li>'.$item['page_name'];
            build_dropdown($item['page_name'], $pages);
            echo '</li>';
        } // END foreach
        echo '</ul>'; 
    } // END if 
}// End Function

By the way, it would be better to start with the function giving build_dropdown($parent = 'none', $pages)

Try this inside your buildDropdown() function..

$items = array();

foreach($pages as $page)
{
    if($page['parent'] == $parent)
    {
        $items[] = $page;
    }
}

if (count($items) > 0)
{
    echo '<ul id="sub_menu_'.$parent.'" class="sub_navagation">';
    foreach($items as $item)
    {
        echo '<li>'.$item['page_name'].'</li>';
    }
    echo '</ul>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM