In a nested menu system, each menu item can have child menu items, which can in turn have their own child items. The goal is to fetch and display these nested menu levels from a database effectively.
To achieve this, we can employ a non-recursive approach that involves:
Here's a PHP function that demonstrates the above approach:
<code class="php">function generateMenu($items) { $html = ''; $parent = 0; $parentStack = array(); $children = array(); foreach ($items as $item) { $children[$item['parent_id']][] = $item; } while (($option = each($children[$parent])) || ($parent > 0)) { if (!empty($option)) { // 1) Item with children if (!empty($children[$option['value']['id']])) { $html .= '<li>' . $option['value']['title'] . '</li>'; $html .= '<ul>'; array_push($parentStack, $parent); $parent = $option['value']['id']; } // 2) Item without children else { $html .= '<li>' . $option['value']['title'] . '</li>'; } } // 3) Current parent has no more children else { $html .= '</ul>'; $parent = array_pop($parentStack); } } return $html; }</code>
To use the function, first retrieve the menu items from the database and pass them as an array to the generateMenu() function. The resulting HTML will be a series of nested unordered lists representing the hierarchical menu structure.
This non-recursive approach eliminates the risk of infinite loops that can occur with recursion, making it a more stable and efficient solution for generating nested menus.
The above is the detailed content of How to Build a Limitless Nested Menu System with PHP and MySQL: A Non-Recursive Approach?. For more information, please follow other related articles on the PHP Chinese website!