Saypontigohe Saypontigohe - 1 month ago 5
PHP Question

menu with while and foreach loop

I am stuck with my current knowledge of PHP. I want to make a menu where the info is stored into a database. What I want to achieve is the following:

<?php
$names= array();
$aliases= array();
$items = array();
?>
<?php while($row = mysqli_fetch_array($menu, MYSQLI_ASSOC)){
$names[] = $row['page'];
$aliases[] = $row['alias'];
$items[] = $row['item'];
}?>

<div id="menu">
<ul>
<?php foreach($names as $page_name){
<a href="*** HERE THE ALIAS CORRESPONDING WITH THE NAME***"><?php echo $page_name;?></a>
?>
*** IF THERE ARE SUB MENU ITEMS, SHOW THEM ***
<ul>
<li>
<a href="*** ALIAS OF SUB ITEM ****">*** NAME OF SUB ITEM***</a>
</li>
</ul>
</ul>
</div>


I have absolutely no idea if i am on the right pad. The foreach works fine for the names or aliasses only, but i want to sort of combine them. Then i want to check if there is a submenu for the hover, but also set the parent item on class "active".

Since it is hard for me to explain it in English, please ask me any question needed so i can provide more info.

Thanks in advance!

Answer

First of all, you don't need three different arrays, only $names array would be enough. Second, change your while() loop in the following way,

while($row = mysqli_fetch_array($menu, MYSQLI_ASSOC)){
    $names[] = array('page_name' => $row['page'], 'alias' => $row['alias'], 'item' => $row['item']);
}

This will create a multidimensional array comprising of name, alias and sub-items.

And finally, display the entire menu in the following way,

<div id="menu">
    <ul>
        <?php foreach($names as $page_array){ ?>
            <a href="<?php echo $page_array['alias']; ?>"><?php echo $page_array['page_name']; ?></a>
            <?php
                if(!empty($page_array['item'])){
                    ?>
                    <ul>
                        <li>
                            <a href="<?php echo $page_array['item']; ?>"><?php echo $page_array['item']; ?></a>
                        </li>
                    </ul>
                    <?php
                }
        } ?>
    </ul>
</div>