php 树形递归操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PerfectUrl/article/details/86682633
表结构
CREATE TABLE `admin_menu` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL DEFAULT '0',
  `order` int(11) NOT NULL DEFAULT '0',
  `title` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `icon` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `uri` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
数据结构
INSERT INTO `admin_menu` VALUES 
('1', '0', '1', 'home', 'fa-home', '/', null, '2018-11-09 10:01:03'), 
('2', '0', '29', '后台管理', 'fa-tasks', null, null, '2019-01-07 18:57:09'), 
('3', '2', '30', '操作者管理', 'fa-users', 'auth/users', null, '2019-01-07 18:57:09'), 
('4', '2', '31', '角色管理', 'fa-user', 'auth/roles', null, '2019-01-07 18:57:09'), 
('5', '2', '32', '权限管理', 'fa-ban', 'auth/permissions', null, '2019-01-07 18:57:09'), 
('6', '2', '33', '菜单栏管理', 'fa-bars', 'auth/menu', null, '2019-01-07 18:57:09'), 
('7', '2', '34', '操作日志', 'fa-history', 'auth/logs', null, '2019-01-07 18:57:09'), 
('8', '0', '2', '用户', 'fa-users', null, '2018-05-23 09:52:18', '2018-12-18 16:33:44'), 
('9', '16', '18', '推荐交易对列表', 'fa-align-justify', 'block/coin/recommend', '2018-05-23 09:52:33', '2018-12-18 16:33:44'), 
('10', '8', '3', '用户列表', 'fa-bars', 'users/list', '2018-05-23 09:53:40', '2018-12-18 16:33:44'), 
('11', '8', '4', '用户资产', 'fa-cc-mastercard', 'users/asset', '2018-05-23 09:56:52', '2018-12-18 16:33:44');
/**
*@desc $result 查询的数据结果
*@desc $parentId 第一次传入的parentId
**/
public static function toTree($result, $parentId = 0){
    $tree = [];
    foreach ($result as $key => $value) {
        //判断当前记录的父ID跟$parentId是否相等
        if ($value->parent_id == $parentId) {
            //进行递归循环 把当前的记录的id当作parentID,在于结果集进行对比找到儿子
            $child = self::digui($result,$value->id);
            //过滤掉空的数组
            if($child){
                $value->child = $child;
            }
            $tree[] = $value;
        }
    }

    return $tree;
}

猜你喜欢

转载自blog.csdn.net/PerfectUrl/article/details/86682633
今日推荐