
多维数组读取无限级分类子分类
在处理含有无限级分类结构的数据时,将结果存储为一维数组可能会造成信息丢失。本文介绍如何修改 php 函数以将一维数组转换为多维数组,以便以层次结构表示分类信息。
具体来说,我们修改了 getchildarea 函数以使用 deal_list_to_tree2 函数执行该转换。修改后的代码如下:
function getchildarea($id) { if (!$id) { return; } static $area; $area = $area ?? new appcommonmodelarea; $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 ] ] ] ] ]]
以上就是如何用PHP高效处理无限级分类数据并转换为多维数组?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1251502.html
微信扫一扫
支付宝扫一扫