Building a menu tree using PHP and MySQL involves presenting a hierarchical list of menu items from a database. This article addresses a user's query on how to achieve this without recursion or hitting the database multiple times.
Data Structure:
The provided example depicts page objects retrieved from a database, where each object has an id, title, and parent_id. A parent_id of null indicates a root-level menu item.
<code class="php">page object id title parent_id</code>
Solution:
The recommended approach involves pre-sorting the menu items in the database to ensure the desired order. This can be done by adding a weight or sequence column to the database schema and ordering the query results by that column.
<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 Output:
Given the provided menu items:
<code class="php">$menu = 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>
Calling build_menu($menu) will produce the following HTML output:
<code class="html"><ul> <li>Menu 1 <ul> <li>Sub 1.1</li> <li>Sub 1.2</li> <li>Sub 1.3</li> </ul> <li>Menu 2 <ul> <li>Sub 2.1 <ul> <li>Sub Sub 2.1.1</li> </ul> <li>Sub 2.2</li> </ul> <li>Menu 3</li> </ul></code>
The above is the detailed content of How to Build a Tree-Structured Menu in PHP Without Recursion or Multiple Database Queries?. For more information, please follow other related articles on the PHP Chinese website!