在生成多级树状数组之前,我们一般得到的数据结构如下
[{
"id": 6,
"parent_id": 5,
"name": "体育专题1",
"intro": "体育专题1111介绍",
}, {
"id": 5,
"parent_id": 4,
"name": "体育专题",
"intro": "体育专题介绍",
}, {
"id": 4,
"parent_id": 0,
"name": "体育",
"intro": "体育所有区块",
}, {
"id": 3,
"parent_id": 1,
"name": "最视频",
"intro": "最视频介绍",
}, {
"id": 2,
"parent_id": 1,
"name": "轮播台",
"intro": "首页轮播台介绍",
}, {
"id": 1,
"parent_id": 0,
"name": "首页",
"intro": "首页的所有区块",
}]
我们需要根据其中的pid(parent_id)与id之间的关系,来将数数组转成多级数组
首先考虑,如果使用递归,递归执行的条件是什么?或者反过来说,递归返回的条件是什么?
假设我们用上述数据的第一个元素pid是5,继续找到id为5的数据找到第二个元素,第二个元素pid为4,继续找id为4的元素,id为4的元素pid为0,说明找到了最后
所以代码如下
$newData = $this->digui($data,0);
function digui($arr, $pid = 0)
{
$newArr = [];
foreach ($arr as $item) {
if ($pid == $item['parent_id']) {
$item['children'] = digui($arr, $item['id']);
$newArr [] = $item;
}
}
return $newArr;
}
$newData = $this->digui($data,0);
传入的data中的元素,而其中的递归相当于找出当前被遍历元素的所有后代元素(包括儿子元素孙子元素)。所以最后我们得到的数据结构如下
[{
"id": 4,
"parent_id": 0,
"name": "体育",
"intro": "体育所有区块",
"created_at": 0,
"updated_at": 0,
"children": [{
"id": 7,
"parent_id": 4,
"name": "体育专题2",
"intro": "体育专题22222介绍",
"created_at": 0,
"updated_at": 0,
"children": []
}, {
"id": 5,
"parent_id": 4,
"name": "体育专题1",
"intro": "体育专题介绍",
"created_at": 0,
"updated_at": 0,
"children": [{
"id": 6,
"parent_id": 5,
"name": "体育专题1-1",
"intro": "体育专题1111介绍",
"created_at": 0,
"updated_at": 0,
"children": []
}]
}]
}, {
"id": 1,
"parent_id": 0,
"name": "首页",
"intro": "首页的所有区块",
"created_at": 0,
"updated_at": 0,
"children": [{
"id": 3,
"parent_id": 1,
"name": "最视频",
"intro": "最视频介绍",
"created_at": 0,
"updated_at": 0,
"children": []
}, {
"id": 2,
"parent_id": 1,
"name": "轮播台",
"intro": "首页轮播台介绍",
"created_at": 0,
"updated_at": 0,
"children": []
}]
}]