Home  >  Article  >  Database  >  How to Build Unlimited-Level Menus with PHP and MySQL: A Recursive Solution?

How to Build Unlimited-Level Menus with PHP and MySQL: A Recursive Solution?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 13:12:30571browse

How to Build Unlimited-Level Menus with PHP and MySQL: A Recursive Solution?

Building Unlimited-Level Menus with PHP and MySQL

To build complex menus with multiple levels and submenus, a common approach involves utilizing a database structure to organize menu items. In such structures, top-level menus typically have a parent ID of 0, while submenus are assigned the ID of their parent menu.

One challenge arises when you need to check for submenus recursively and display them within their respective list items. Here's how to accomplish this using PHP and MySQL:

MySQL Query:

SELECT id, parent_id, name, link, position
FROM menu_item
ORDER BY parent_id, position;

This query fetches all menu items in a hierarchical order based on their parent-child relationships.

PHP Implementation:

<code class="php">$html = '';
$parent = 0; // Starting with the top-level menu
$parent_stack = array(); // Keeps track of parent menu IDs

// Map menu items by their parent ID
$children = array();
foreach ($items as $item) {
    $children[$item['parent_id']][] = $item;
}

while (
    // If there are more children at the current parent level
    ($option = each($children[$parent])) ||
    // Or if we need to backtrack to a previous parent level
    ($parent > 0)
) {
    if (!empty($option)) {
        // Handle menu items with children
        if (!empty($children[$option['value']['id']])) {
            $html .= '<li>' . $option['value']['name'] . '</li>';
            $html .= '<ul class="submenu">';
            array_push($parent_stack, $parent); // Push current parent ID to the stack
            $parent = $option['value']['id']; // Set current parent to the current menu item's ID
        }
        // Handle menu items without children
        else {
            $html .= '<li>' . $option['value']['name'] . '</li>';
        }
    } else {
        // Backtrack to the previous menu level
        $html .= '</ul>';
        $parent = array_pop($parent_stack); // Pop the last parent ID from the stack
    }
}

// Output the resulting HTML
echo $html;</code>

Explanation:

  1. The PHP code creates a stack to keep track of parent menu IDs ($parent_stack).
  2. It loops through the menu items based on their parent-child relationships.
  3. If a menu item has children, it is added to the end of the HTML output string with a nested
      for its submenu.
    • The current parent ID is pushed onto the stack, and the current parent is set to the current menu item's ID.
    • If a menu item has no children, it is simply added to the HTML output string as a
    • .
    • If there are no more children at the current parent level or if the stack is not empty, the current parent is popped from the stack, and the current parent is set to the popped ID.
    • The loop continues until all menu items have been processed.

This approach provides a flexible and efficient way to build menus with unlimited levels of submenus without the risk of infinite loops that can occur with recursion.

The above is the detailed content of How to Build Unlimited-Level Menus with PHP and MySQL: A Recursive Solution?. 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