Home >Database >Mysql Tutorial >How can I create a recursive PHP function to generate a hierarchical menu tree from a MySQL database table?
Echoing Menu Tree with Recursive Function
To generate a hierarchical menu tree from a database table using a recursive function, consider the following approach:
Problem:
You wish to create a recursive function that extracts a hierarchical menu tree from a MySQL database.
Situation:
The table contains columns:
Expected HTML Output:
<li><a href="#"><p class="Tier0">Datori</p></a> <ul style="display: block"> <li><a href="#"><p class="Tier1">Cookies</p></a></li> <li><a href="#"><p class="Tier1">Events</p></a></li> <li><a href="#"><p class="Tier1">Forms</p></a></li> <li><a href="#"><p class="Tier1">Games</p></a></li> <li><a href="#"><p class="Tier1">Images</p></a> <ul> <li><a href="#"><p class="Tier2">CSS</p></a></li> <li><a href="#"><p class="Tier2">JavaScript</p></a></li> <li><a href="#"><p class="Tier2">JQuery</p></a></li> </ul> </li> <li><a href="#"><p class="Tier1">Navigations</p></a> <ul> <li><a href="#"><p class="Tier2">CSS</p></a></li> <li><a href="#"><p class="Tier2">JavaScript</p></a></li> <li><a href="#"><p class="Tier2">JQuery</p></a></li> </ul> </li> <li><a href="#"><p class="Tier1">Tabs</p></a></li> </ul> </li> <li><a href="#"><p class="Tier0">Washing Machines</p></a></li>
Proposed PHP Function:
<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>'; $ret .= $this->recurse($categories, $category['id'], $level+1); $ret .= '</li>'; } } return $ret . '</ul>'; }</code>
Usage:
Additional Considerations:
The above is the detailed content of How can I create a recursive PHP function to generate a hierarchical menu tree from a MySQL database table?. For more information, please follow other related articles on the PHP Chinese website!