可以使用 php 递归函数创建多级菜单,通过不断调用自身,迭代地生成菜单结构。代码示例演示了递归函数的使用,并提供了数据示例和生成的 html 菜单,实现多级菜单的创建。

使用 PHP 递归函数创建多级菜单
在 PHP 中,递归函数可以通过不断调用自身来解决复杂问题。递归对于创建多级菜单非常有用,因为菜单可能包含多个层级。
代码:
立即学习“PHP免费学习笔记(深入)”;
以下代码演示了如何使用递归函数创建多级菜单:
function createMenu($data, $parent = 0) {
$html = '<ul>';
foreach ($data as $item) {
if ($item['parent_id'] == $parent) {
$html .= '<li><a href="' . $item['url'] . '">' . $item['name'] . '</a>';
$html .= createMenu($data, $item['id']);
$html .= '</li>';
}
}
$html .= '</ul>';
return $html;
}
$data = array(
array('id' => 1, 'parent_id' => 0, 'name' => 'Home', 'url' => 'index.php'),
array('id' => 2, 'parent_id' => 1, 'name' => 'Products', 'url' => 'products.php'),
array('id' => 3, 'parent_id' => 1, 'name' => 'Services', 'url' => 'services.php'),
array('id' => 4, 'parent_id' => 2, 'name' => 'Laptops', 'url' => 'laptops.php'),
array('id' => 5, 'parent_id' => 2, 'name' => 'Desktops', 'url' => 'desktops.php'),
array('id' => 6, 'parent_id' => 3, 'name' => 'Web Design', 'url' => 'web-design.php'),
array('id' => 7, 'parent_id' => 3, 'name' => 'SEO', 'url' => 'seo.php'),
);
echo createMenu($data);实战案例:
以上代码生成以下 HTML 菜单:
<ul> <li><a href="index.php">Home</a></li> <li><a href="products.php">Products</a> <ul> <li><a href="laptops.php">Laptops</a></li> <li><a href="desktops.php">Desktops</a></li> </ul> </li> <li><a href="services.php">Services</a> <ul> <li><a href="web-design.php">Web Design</a></li> <li><a href="seo.php">SEO</a></li> </ul> </li> </ul>
以上就是如何使用 PHP 递归函数创建多级菜单的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号