Themiller
Themiller

Reputation: 33

Create a menu from database (mixed sub menus)

I created a database to store a menu informations with 3 level (2 sub menus level). You can see it on the left here : https://volt-services.fr/sites/stge/index.php#

Here is the table in the database:

enter image description here

And the code to translate it to HTML:

<?php 

$req = $DB->query("SELECT * FROM menu ORDER BY ordered"); 

foreach ($req as $r) { 

  if($r->level == 1) {

    $tab[$r->ordered] = array($r->id,$r->name,$r->class,$r->icon);
    
  } elseif ($r->level == 2) {

    $tab[$r->parent][4][$r->ordered] = array($r->id,$r->name);

  } elseif ($r->level == 3) {

    $tab[$r->cat][4][$r->parent][2][$r->ordered] = array($r->id,$r->name);

  }

}

foreach ($tab as $key => $value) {

?>

<li data-menu="<?= $value[0]; ?>" class="<?= $value[2]; ?> menu-item">
<span class="material-icons-outlined"><?= $value[3];  ?></span>  
<span class="titre_menu">&nbsp;<?= $value[1]; ?></span>

    <ul id="sub_menu<?= $value[0]; ?>" class="box_sub_exp <?= $value[2]; ?>">

    <?php foreach ($value[4] as $ke => $val) { // SUB MENU POSITION 4 ?>

        <li class="<?= $value[2]; ?> submenu-item"><a href="page.php?=<?= $val[0]; ?>"><?= $val[1]; ?></a>

      <?php if(!empty($val[2])) { // IS A MENU IN POSITION 2 ?> 

            <ul class="box_sub_sub_exp">

        <?php foreach ($val[2] as $k => $v) { // SUB MENU POSITION 2 ?>
        
                <li class="<?= $value[2]; ?> submenu-item"><a href="page.php?=<?= $v[0]; ?>"><?= $v[1]; ?></a></li>
  
        <?php } ?>

            </ul>

      <?php } ?>

        </li>

  <?php } ?>

    </ul>

</li>

<?php } ?>

</ul>
</nav>


 </section>

On the first sub menu everything is OK. But on the second, the first line is missing, on the third 2 first lines are missing, etc... I think there is a problem with my loop, could you please help me to find it ?

FIXED : the problem was in the request, not "ORDER BY ordered" but by "id"

Upvotes: 0

Views: 527

Answers (1)

Camille
Camille

Reputation: 879

Even if you set a numeric key with $r->ordered, you have to sort your table before your display loop ! Give a numeric key to a table line doesn't "auto-sort" it on loop.

Try using ksort() on $tab before your display foreach. So it's will use keys you've define and sort your table in order.

Upvotes: 2

Related Questions