多维数组读取无限级分类子分类
在处理含有无限级分类结构的数据时,将结果存储为一维数组可能会造成信息丢失。本文介绍如何修改 php 函数以将一维数组转换为多维数组,以便以层次结构表示分类信息。
具体来说,我们修改了 getchildarea 函数以使用 deal_list_to_tree2 函数执行该转换。修改后的代码如下:
function getchildarea($id) { if (!$id) { return; } static $area; $area = $area ?? new ppcommonmodelrea; $result = collection($area->where(['pid' => $id])->order('id desc')->select())->toarray(); static $res = []; if ($result) { foreach ($result as $key => $val) { $res[] = $val; $res[$key]['children_list'] = getchildarea($val['id']); // 按层次递归生成子分类 } } return $res; }
修改后,调用 deal_list_to_tree2 函数:
立即学习“PHP免费学习笔记(深入)”;
$multidimensionalarray = deal_list_to_tree2(getchildarea(1));
这样,我们就可以获得一个包含多层级子分类的多维数组:
[ [ 'id' => 1, 'area_name' => '安徽省', 'pid' => 0, 'level' => 1, 'children_list' => [ [ 'id' => 4, 'area_name' => '合肥市', 'pid' => 1, 'level' => 2, 'children_list' => [ [ 'id' => 7, 'area_name' => '肥东县', 'pid' => 4, 'level' => 3, 'children_list' => [ [ 'id' => 8, 'area_name' => '桃园镇', 'pid' => 7, 'level' => 4, 'children_list' => [ [ 'id' => 9, 'area_name' => '八斗乡', 'pid' => 8, 'level' => 5 ] ] ] ] ], [ 'id' => 10, 'area_name' => '长丰县', 'pid' => 4, 'level' => 3 ] ] ] ] ] ]