PHP/MySQL Unordered List Menu Tree Construction: A Non-Recursive Single Database Query Approach
Building unordered list menu trees from database queries is a common task. Typically, recursive functions that query the database multiple times are employed. However, a more efficient non-recursive approach is possible using a single database query.
Given an array of page objects with id, title, and parent_id attributes, the goal is to create a function that generates the HTML for an unordered list menu.
Solution:
Our solution employs the following steps:
Code:
<code class="php">function has_children($rows, $id) { foreach ($rows as $row) { if ($row['parent_id'] == $id){ return true; } } return false; } function build_menu($rows, $parent=0) { $result = "<ul>"; foreach ($rows as $row) { if ($row['parent_id'] == $parent){ $result.= "<li>{$row['title']}"; if (has_children($rows,$row['id'])) { $result.= build_menu($rows,$row['id']); } $result.= "</li>"; } } $result.= "</ul>"; return $result; }</code>
Example Usage:
<code class="php">$menu = [ ['id' => 1, 'title' => 'Menu 1', 'parent_id' => null], ... // Additional menu objects ]; echo build_menu($menu); // Outputs the complete menu list</code>
Advantages:
The above is the detailed content of How to Build an Unordered List Menu Tree in PHP/MySQL Without Recursion?. For more information, please follow other related articles on the PHP Chinese website!