Echoing Menu Tree with Recursive Function
In the scenario where you have a MySQL database with hierarchical data organized under various roots, you may encounter the need to generate an HTML menu tree replicating this structure. This involves displaying the root categories and their subcategories recursively.
To accomplish this, a recursive PHP function can be employed to traverse the database records and construct the HTML markup. The function requires the categories data and optionally a parent identifier and depth level.
The function iterates through the categories, searching for elements that match the specified parent. If a match is found, it generates an
The following revised PHP function incorporates optimizations to prevent empty
<code class="php">function recurse($categories, $parent = null, $level = 0) { $ret = '<ul>'; foreach ($categories as $index => $category) { if ($category['root'] == $parent) { $ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>'; $sub = $this->recurse($categories, $category['id'], $level + 1); if ($sub != '<ul></ul>') { $ret .= $sub; } $ret .= '</li>'; } } return $ret . '</ul>'; }</code>
To improve performance, it is advisable to query the database to include a field indicating the number of child categories for each category. This information can be utilized to determine whether to recursively traverse child categories:
<code class="php">select Category.*, (select count(distinct c1.id) from Category as c1 where c1.root = Category.id) as ChildCount from Category</code>
With this enhancement, the recurse function can be modified accordingly:
<code class="php">function recurse($categories, $parent = null, $level = 0) { $ret = '<ul>'; foreach ($categories as $index => $category) { if ($category['root'] == $parent) { $ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>'; if ($category['ChildCount'] > 0) { $ret .= $this->recurse($categories, $category['id'], $level + 1); } $ret .= '</li>'; } } return $ret . '</ul>'; }</code>
The above is the detailed content of How can I efficiently generate an HTML menu tree from hierarchical data stored in a MySQL database using a recursive PHP function?. For more information, please follow other related articles on the PHP Chinese website!