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:
$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 .= '' . $option['value']['name'] . ' ';
$html .= ' ';
$parent = array_pop($parent_stack); // Pop the last parent ID from the stack
}
}
// Output the resulting HTML
echo $html;
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3