Flat Data to Hierarchical Nested Menu:
Building an unordered list menu tree from a database can be a common task in web development. To achieve this in PHP and MySQL, without resorting to recursion and database querying, you can utilize a single-pass algorithm to process your page objects.
The provided page objects have a parent_id attribute, indicating parent-child relationships. To construct the menu tree, you'll need a function like this:
<code class="php">function build_menu($page_objects) { // Create an array to store parent-child relationships $parents = array(); // Loop through the page objects foreach ($page_objects as $page) { $parents[$page['id']] = $page['parent_id']; } // Initialize the menu string $menu = ''; // Loop through the page objects again foreach ($page_objects as $page) { // Check if the current page has no parent (root page) if (!isset($parents[$page['id']])) { $menu .= "<ul><li>{$page['title']}"; } // Handle child pages else { $parent_id = $parents[$page['id']]; // Find the parent 'ul' tag for the child page $parent_index = strrpos($menu, "<li>{$page_objects[$parent_id]['title']}"); // Append the child page to the parent 'ul' tag $menu = substr_replace($menu, "<li>{$page['title']}", $parent_index + strlen($page_objects[$parent_id]['title']) + 4, 0); } // Close the 'li' tag $menu .= '</li>'; // Handle closing the 'ul' tag for root pages if (!isset($parents[$page['parent_id']])) { $menu .= "</ul>"; } } return $menu; }</code>
Usage:
For example, with the provided page objects:
<code class="php">$page_objects = array( array('id' => 1, 'title' => 'Menu 1', 'parent_id' => null), array('id' => 2, 'title' => 'Sub 1.1', 'parent_id' => 1), array('id' => 3, 'title' => 'Sub 1.2', 'parent_id' => 1), array('id' => 4, 'title' => 'Sub 1.3', 'parent_id' => 1), array('id' => 5, 'title' => 'Menu 2', 'parent_id' => null), array('id' => 6, 'title' => 'Sub 2.1', 'parent_id' => 5), array('id' => 7, 'title' => 'Sub Sub 2.1.1', 'parent_id' => 6), array('id' => 8, 'title' => 'Sub 2.2', 'parent_id' => 5), array('id' => 9, 'title' => 'Menu 3', 'parent_id' => null) );</code>
You can generate the menu tree by calling the function:
<code class="php">$menu_html = build_menu($page_objects);</code>
This will produce the desired HTML list representing the nested menu structure.
The above is the detailed content of How to Efficiently Transform Flat Data into a Hierarchical Nested Menu in PHP and MySQL without Recursion?. For more information, please follow other related articles on the PHP Chinese website!