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:
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!