Home >Database >Mysql Tutorial >How to Build Hierarchical Menus With Unlimited Depth in PHP and MySQL?

How to Build Hierarchical Menus With Unlimited Depth in PHP and MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 22:20:02758browse

How to Build Hierarchical Menus With Unlimited Depth in PHP and MySQL?

Building Hierarchical Menus with Unlimited Depth

In this guide, we'll explore how to create nested menus with an unlimited number of levels using PHP and MySQL.

Database Structure

We'll use a database structure where each menu item has an "id," "parent_id," and "title." The "parent_id" field stores the ID of the menu item's parent, with "0" indicating a top-level menu.

Fetching Submenus

To fetch submenus for a parent menu, we can use the following code:

<code class="php"><?php
$list = $obj->childmenu($parentid); 

foreach($list as $menu) {
    extract($menu);
    echo '<li><a href="#">'.$name.'</a></li>';
}
?></code>

Checking for Child Submenus

To check if a menu has child submenus, we can modify the above code as follows:

<code class="php"><?php
$list = $obj->childmenu($parentid); 

foreach($list as $menu) {
    extract($menu);
    if (count($obj->childmenu($id)) > 0) {
        echo '<li><a href="#">'.$name.'</a><ul class="submenu">';
        $list2 = $obj->childmenu($id); 
        foreach($list2 as $menu2) {
            extract($menu2);
            echo '<li><a href="#">'.$name.'</a></li>';
        }
        echo '</ul>
        </li>';
    } else {
        echo '<li><a href="#">'.$name.'</a></li>';
    }
}
?></code>

This code uses a nested loop to fetch and display submenus, ensuring that all levels of the hierarchy are captured. The result will be a nested HTML structure with menu items and their corresponding submenus.

The above is the detailed content of How to Build Hierarchical Menus With Unlimited Depth in PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn