无限极分类转树结构
权限功能或者是菜单功能,面对层级比较深,需要转换成树结构时,可通过以下方式实现。
/**
* 把返回的数据集转换成Tree - 此函数摘录自网络
* @param array $list 要转换的数据集
* @param string $pk parent标记字段
* @param string $pid level标记字段
* @param string $child
* @param int $root
* @return array
* User: zhangwei
* Date: 2021/9/7 15:48
*/
public function listToTree(array $list, string $pk='parent_id', string $pid = 'level', string $child = 'children', int $root = 3): array
{
// 创建Tree
$tree = array();
if(is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
/**
* 获取权限树
* @return array
* @throws \Exception
* User: zhangwei
* Date: 2021/9/23 10:09
*/
public function ruleTreeNew(): array
{
$rule_model = new UserAuthRule();
$list = $rule_model->getDataList([
['status','=',1]
]);
$tree = $this->ruleTreeListDeal($list,0);
return $tree;
}
public function ruleTreeListDeal($list,$pid): array
{
// listToTree方法在上方以贴出。
$ret = (new Dept())->listToTree($list,'pid','pid','children',$pid);
foreach ($ret as &$value) {
$ret2 = $this->ruleTreeListDeal($list,$value['id']);
if(empty($ret2)){
$ret2 = null;
}
$value['children'] = $ret2;
}
return $ret;
}
调用ruleTreeNew方法
返回结果:
{
"code": 1,
"msg": "",
"data": [
{
"id": 1,
"name": "首页",
"title": "首页",
"path": "/",
"component": "[Layout]",
"redirect": "dashboard",
"pid": 0,
"status": 1,
"icon": "dashboard",
"rank": 0,
"is_interface": 0,
"is_menu": 1,
"is_cache": 1,
"is_affix": 1,
"create_time": "2021-09-02 16:53:05",
"update_time": "2021-09-11 17:20:37",
"operator_id": 1,
"remark": "",
"children": [
{
"id": 59,
"name": "首页",
"title": "首页",
"path": "dashboard",
"component": "dashboard/index",
"redirect": "",
"pid": 1,
"status": 1,
"icon": "dashboard",
"rank": 0,
"is_interface": 0,
"is_menu": 1,
"is_cache": 1,
"is_affix": 1,
"create_time": "2021-09-11 11:56:53",
"update_time": "2021-09-11 11:56:53",
"operator_id": 1,
"remark": "",
"children": null
}
]
}
]
}