PHP根据pid一维数组转为多维数组
代码:
/**
* 方法 dealListToTree,一维数组根据$parent_id的值转为多维数组
*
* @param array $data 待处理的一维数组
* @param string $pkName 用于转化为多维数组的主键字段
* @param string $pIdName 用于转化为多维数组的字段(根据该字段值转换)
* @param string $childName 子级的字段名
* @param string $sortKey 排序字段(不需要可以单独去掉)
* @param bool $is_empty_childrens 是否返回空的子数组(childrens[])(true:是,false:否)
* @param string $rootId 根节点$pkName值
*
* @return array $new_data 返回处理好的(多层级)多维数组
*
*/
public function dealListToTree($data, $pkName='id', $pIdName='pid', $childName='children', $sortKey='sort', $is_empty_childrens=false, $rootId=0)
{
$new_data = [];
foreach($data as $sorData){
if($sorData[$pIdName] == $rootId){
$res = $this->dealListToTree($data, $pkName, $pIdName, $childName, $sortKey, $is_empty_childrens, $sorData[$pkName]);
if(!empty($res) && !$is_empty_childrens){
if(array_key_exists($childName, $sorData)) {
if(array_key_exists($childName, $sorData)){
$sorData[$childName]['sort'] = $res[0];
}else{
$sorData[$childName]['sort'] = $res;
}
}else{
$sorData[$childName] = $res;
}
//对子数组做排序
array_multisort(array_column($sorData[$childName], $sortKey),SORT_ASC, $sorData[$childName]);
}
$new_data[] = $sorData;
}
}
//对最外层数组做排序
array_multisort(array_column($new_data, $sortKey),SORT_ASC, $new_data);
return $new_data;
}
}
返回结果示例:
{
"code": 0,
"msg": "success",
"data": [
{
"id": 4,
"title": "4",
"name": "ceshi_xiugai",
"is_menu": 1,
"pid": 0,
"sort": 1
},
{
"id": 3,
"title": "3",
"name": "user/updateUserInfo",
"is_menu": 1,
"pid": 0,
"sort": 2,
"children": [
{
"id": 12,
"title": "11",
"name": "jiedian4",
"is_menu": 1,
"pid": 3,
"sort": 1,
"children": [
{
"id": 17,
"title": "16",
"name": "AuthRule/update",
"is_menu": 1,
"pid": 12,
"sort": 1
},
{
"id": 16,
"title": "15",
"name": "操作3",
"is_menu": 1,
"pid": 12,
"sort": 2
}
]
},
{
"id": 13,
"title": "12",
"name": "jiedian5",
"is_menu": 1,
"pid": 3,
"sort": 2
}
]
},
{
"id": 1,
"title": "1",
"name": "ceshi_xiugai2",
"is_menu": 1,
"pid": 0,
"sort": 3,
"children": [
{
"id": 9,
"title": "8",
"name": "jiedian2",
"is_menu": 1,
"pid": 1,
"sort": 1
},
{
"id": 5,
"title": "5",
"name": "erji/caidan",
"is_menu": 1,
"pid": 1,
"sort": 2,
"children": [
{
"id": 10,
"title": "9",
"name": "节点2",
"is_menu": 1,
"pid": 5,
"sort": 1,
"children": [
{
"id": 18,
"title": "1",
"name": "cs_tjia",
"is_menu": 1,
"pid": 10,
"sort": -1
},
{
"id": 15,
"title": "14",
"name": "操作2",
"is_menu": 1,
"pid": 10,
"sort": 1
},
{
"id": 14,
"title": "13",
"name": "操作1",
"is_menu": 1,
"pid": 10,
"sort": 2
}
]
}
]
}
]
},
{
"id": 2,
"title": "2",
"name": "user_restPwd",
"is_menu": 1,
"pid": 0,
"sort": 4,
"children": [
{
"id": 7,
"title": "6",
"name": "2级菜单",
"is_menu": 1,
"pid": 2,
"sort": 1
},
{
"id": 8,
"title": "7",
"name": "节点1",
"is_menu": 1,
"pid": 2,
"sort": 1
}
]
}
]
}
注:转载大佬的文章,原文链接点这里