递归获得无限极tree

雨中笑 php 网站 475热度

简介获取多级菜单栏递归的实现方式

本博客在做菜单栏时是利用一张表格实现存储多级菜单栏数据的,这种利用一张表格递归获取无限级tree可以利用到很多场景的,  多楼层的留言数据,多级分类,书签等等。

本案例是根据博客的菜单栏来设计:


CREATE TABLE `blog_nav` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父级id',
`name` varchar(36) DEFAULT NULL,
`link` varchar(220) DEFAULT NULL COMMENT '链接',
`other` varchar(255) DEFAULT NULL COMMENT '其它标签如跳转',
`opr_id` int(11) NOT NULL DEFAULT '0' COMMENT '操作人',
`status` tinyint(1) DEFAULT '1' COMMENT '0不可见,1可见',
`updated_at` datetime DEFAULT NULL,
`create_time` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `parent_id` (`parent_id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4;

parent_id等于0代表最高父级,其余级数根据id来定

递归排序tree代码:

/**
* 获得多级tree
* @author: Fanjialong<1171843306@qq.com>
* @datetime: 2020-08-28
* @return array
*/
public function getNavs(){
$where = [];
$where['status'] = 1;
$data = BlogNav::select(['id','parent_id','name','link','other'])->where($where)->get()->toArray();
$parent = [];
$child = [];
foreach ($data as $val){
$val['parent_id'] == 0 ? $parent[] = $val : $child[] = $val;
}

$rs = [];
$i = 0;
foreach ($parent as $val){
$rs[$i]['value'] = $val['id'];
$rs[$i]['name'] = $val['name'];
$rs[$i]['url'] = $val['link'];
$rs[$i]['other'] = $val['other'] ? $val['other'] : '';
$children = $this->getNav($val['id'],$child);
$rs[$i]['children'] = $children;
$i++;
}
return $rs;
}

/**
* 递归获取子集
* @author: Fanjialong<1171843306@qq.com>
* @datetime: 2020-08-28
* @param $id
* @param $data
* @return array
*/
public function getNav($id,$data){
$rs = [];
$i = 0;
foreach ($data as $val){
if($val['parent_id'] == $id){
$rs[$i]['value'] = $val['id'];
$rs[$i]['name'] = $val['name'];
$rs[$i]['url'] = $val['link'];
$rs[$i]['other'] = $val['other'] ? $val['other'] : '';
$children = $this->getNav($val['id'],$data);
$rs[$i]['children'] = $children;
$i++;
}
}
return $rs;
}

输出后可获得


一般比较复杂的递归,数据又不经常变动的可以直接存储在缓存中

$this->Nav = Cache::rememberForever('BlogNav', function () {
return $this->getNavs();
});

以上就是具体代码和思路,换着改改很多场景都是可以适用的,我工作中客服系统的 工单类型也是采用这种设置思路


很赞哦!(1)

本文阅读量 1659发布于 2020年8月28日

您的访问IP 3.144.237.122最早于 2024年5月14日 16时39分00秒 阅读过本文 为本文提供了 1 热度 1 阅读量

文章评论
回帖