PHP多层级菜单树形结构递归处理

如题:

一、数据库菜单数据表

使用图片中id和parent_id两个参数来关联父子关系

image

二、将数据库中的数据变成树状多层级解构

```
{
	"id": 1,
	"parentId": 0,
	"treePath": "0",
	"name": "系统管理",
	"type": 2,
	"path": "/system",
	"component": "Layout",
	"perm": null,
	"visible": 1,
	"sort": 1,
	"icon": "system",
	"redirect": "/system/user",
	"createTime": "2021-08-28 09:12:21",
	"updateTime": "2021-08-28 09:12:21",
	"level": 0,
	"children": [
		{
			"id": 2,
			"parentId": 1,
			"treePath": "0,1",
			"name": "用户管理",
			"type": 1,
			"path": "user",
			"component": "system/user/index",
			"perm": null,
			"visible": 1,
			"sort": 1,
			"icon": "user",
			"redirect": null,
			"createTime": "2021-08-28 09:12:21",
			"updateTime": "2021-08-28 09:12:21",
			"level": 1,
			"children": [
				{
					"id": 31,
					"parentId": 2,
					"treePath": "0,1,2",
					"name": "用户新增",
					"type": 4,
					"path": "",
					"component": null,
					"perm": "sys:user:add",
					"visible": 1,
					"sort": 1,
					"icon": "",
					"redirect": "",
					"createTime": "2022-10-23 11:04:08",
					"updateTime": "2022-10-23 11:04:11",
					"level": 2
				},
				...
				// 多层级省略
			]
		},
		...
		// 多层级省略
    ]
},
...
// 多层级省略
```

三、实现方法

```
	// 1、先获取数据
	$model = new SysMenu();
	$data = $model->getDbAll();
	
	// 2、重点: 组装菜单menus,可将该方法提取出来
	function filterMenus($data, $pid = 0, $level = 0)
	{
		// $level 是可选
		$tree = [];
		foreach($data as $k => $v) {
			if ($v['parent_id'] === $pid) {
				$v['level'] = $level;
				$child = filterMenus($data, $v['id'], $level+1);
				if (!empty($child)) {
					// 自定义children字段,存放子数据
					$v['children'] = $child;
				}
				// 将$v push到$tree中,多维数组
				$tree[] = $v;
			}
		}
		return $tree;
	}
	
	// 3、调用函数
	$menus = filterMenus($data, 0);
	
	// 4、打印结果
	var_dump($menus);die;
```

以上即可完成菜单转化,重点是数据表中两个关联字段id、parent_id和递归函数;

posted @ 2023-09-21 10:40  浪里小韭菜  阅读(17)  评论(0编辑  收藏  举报