PHP无限极菜单
权限表结构
CREATE TABLE `blog_auth` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '序号', `pid` int(11) NOT NULL COMMENT '父级ID', `auth_name` varchar(191) NOT NULL COMMENT '权限名字', `auth_title` varchar(191) NOT NULL COMMENT '权限标题', `auth_icon` varchar(191) DEFAULT NULL COMMENT '权限图标', `auth_rule` varchar(191) NOT NULL COMMENT '权限路径', `menu` tinyint(1) NOT NULL COMMENT '菜单 1=>显示菜单,0=>不显示菜单', `debug` tinyint(1) NOT NULL COMMENT '调试模式 1-->仅调试模式显示,0-->任何时候都显示', `create_by` int(11) NOT NULL COMMENT '创建人', `update_by` int(11) NOT NULL COMMENT '更新人', `create_time` int(11) NOT NULL COMMENT '创建时间', `update_time` int(11) NOT NULL COMMENT '更新时间', `delete_time` int(11) NOT NULL COMMENT '删除时间', `sort` int(11) NOT NULL COMMENT '排序字段', `status` tinyint(1) NOT NULL COMMENT '状态', PRIMARY KEY (`id`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
相关代码
/** * @title 菜单列表 * @param int $uid * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException */ public function getMenuList($uid = 0) {//展示只有菜单类型的权限列表 $auth_list_info = Db::name('auth')->field(['id','pid','auth_title','auth_rule'])->select(); if ($auth_list_info === null){return [];} $auth_list_info = is_array($auth_list_info) ? $auth_list_info : $auth_list_info->toArray(); return $this->getSonsInfo($auth_list_info); } /** * @title 菜单树生成 * @param array $items - 数据 * @param int $pid - 父级ID的值 * @param int $deep - 深度 * @return array */ protected function getSonsInfo(array $items,$pid=0,$deep=0) { $lists = []; foreach ($items as $item){ if ($item['pid'] === $pid){ $item['deep'] = $deep; $item['son'] = $this->getSonsInfo($items,$item['id'],$deep+1); $lists[] = $item; } } return $lists; }
打印结果
Array ( [0] => Array ( [id] => 1 [pid] => 0 [auth_title] => 博客后台人员账户 [auth_rule] => backend/account/default [deep] => 0 [son] => Array ( [0] => Array ( [id] => 2 [pid] => 1 [auth_title] => 博客后台人员账户列表页 [auth_rule] => backend/account/index [deep] => 1 [son] => Array ( ) ) ) ) [1] => Array ( [id] => 9 [pid] => 0 [auth_title] => 博客后台首页 [auth_rule] => backend/index/default [deep] => 0 [son] => Array ( [0] => Array ( [id] => 10 [pid] => 9 [auth_title] => 博客后台首页 [auth_rule] => backend/index/index [deep] => 1 [son] => Array ( ) ) ) ) [2] => Array ( [id] => 19 [pid] => 0 [auth_title] => 博客后台文章管理 [auth_rule] => backend/article/default [deep] => 0 [son] => Array ( [0] => Array ( [id] => 20 [pid] => 19 [auth_title] => 博客后台文章列表页 [auth_rule] => backend/article/index [deep] => 1 [son] => Array ( ) ) ) ) )