Home >Database >Mysql Tutorial >How to Create an Echo Menu Tree Using a Recursive Function in PHP?
Creating a recursive function to traverse a hierarchical menu structure stored in a database and output it in HTML can be challenging. Given a table with categories and their parent categories, the task is to generate a menu tree that visually represents the hierarchy.
To solve this problem, a recursive function is needed. The idea is to start with the root category, find its children, and recursively call the function on each child, building up the HTML output as we go.
Here is a possible implementation of the 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>
To use the function:
The initial implementation may produce 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>
This modification ensures that only categories with children have
Alternatively, you can add a child count to each category and only include the
The above is the detailed content of How to Create an Echo Menu Tree Using a Recursive Function in PHP?. For more information, please follow other related articles on the PHP Chinese website!