When writing the backend management system of the tp framework, this problem occurred when writing the left navigation bar. I have been looking for a long time but I still haven’t found a solution. Can you please help me!
大瓶可乐@php.cn2023-06-29 01:27:16
Function
function displayMenu($menuItems, $parentId = 0) { // 获取当前层级的菜单项 $subMenu = array_filter($menuItems, function($item) use ($parentId) { return $item['parent_id'] == $parentId; }); if (empty($subMenu)) { return; } echo '<ul>'; foreach ($subMenu as $item) { echo '<li>'; echo $item['name']; displayMenu($menuItems, $item['id']); echo '</li>'; } echo '</ul>';}
Use function
$menuItems = [ ['id' => 1, 'name' => '首页', 'parent_id' => 0], ['id' => 2, 'name' => '关于我们', 'parent_id' => 0], ['id' => 3, 'name' => '新闻', 'parent_id' => 0], ['id' => 4, 'name' => '公司简介', 'parent_id' => 2], ['id' => 5, 'name' => '团队', 'parent_id' => 2], ['id' => 6, 'name' => '产品动态', 'parent_id' => 3], ['id' => 7, 'name' => '行业新闻', 'parent_id' => 3], ['id' => 8, 'name' => '联系我们', 'parent_id' => 0], ['id' => 9, 'name' => '招聘信息', 'parent_id' => 8],]; displayMenu($menuItems);
Result
-Homepage
-About Us
-Company Profile
- Team
- News
- Product News
- Industry News
- Contact Us
- Recruitment Information