Home >Database >Mysql Tutorial >How can recursion be used to generate a nested menu tree from a database with parent categories?
Recursion for Menu Tree Generation
In your situation, you have a database structure where categories have a 'root' field indicating their parent category. The HTML output you desire involves nested lists representing the category hierarchy. To achieve this, a recursive PHP function can be employed.
Here's an example 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>
This function assumes that root categories have a 'root' field with a null value. It iterates through the categories, identifies child categories based on their 'root' field, and constructs the HTML using nested lists.
To use this function:
Optionally, you can modify the function to avoid empty lists by checking if the category has child categories before creating the list:
<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 modified function will only create lists if the category has at least one child.
The above is the detailed content of How can recursion be used to generate a nested menu tree from a database with parent categories?. For more information, please follow other related articles on the PHP Chinese website!