ThinkPHP框架中如何将无限级分类的一维数组转换为多维数组?

ThinkPHP框架中如何将无限级分类的一维数组转换为多维数组?

无限级分类子分类读取

问题:

如何使用 thinkphp 框架读取无限级分类中的所有子分类,并以多维数组形式返回?

解决方案:

立即学习PHP免费学习笔记(深入)”;

首先,要解决这个问题,我们需要创建一个函数 getchildarea 来读取子分类,该函数将以给定的地区 id 作为参数,并以递归方式遍历所有子分类。

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;             getchildarea($val['id']);         }     }     return $res; }

然而,这个函数返回的是一维数组。要获得多维数组,我们需要将一维数组转换为多维数组。我们可以使用 deal_list_to_tree2 函数来实现此目的:

function deal_list_to_tree2($data, $pkname = 'id', $pidname = 'parent_id', $childname = 'children_list', $is_empty_childrens = false, $rootid = '') {     $new_data = [];     if (!empty($data)) {         foreach ($data as $sordata) {             if (array_key_exists($childname, $sordata) && !empty($sordata[$childname])) {                 $res = deal_list_to_tree2($data, $pkname, $pidname, $childname, $is_empty_childrens, $sordata[$pkname]);             } else {                 if ($sordata[$pidname] == $rootid) {                     if ($sordata[$pkname] != $rootid) {                         $res = deal_list_to_tree2($data, $pkname, $pidname, $childname, $is_empty_childrens, $sordata[$pkname]);                     }                     if (!empty($res) && !$is_empty_childrens) {                         if (array_key_exists($childname, $sordata)) {                             if (array_key_exists($childname, $sordata)) {                                 for ($i = 0; $i < count($res); $i++) {                                     $sordata[$childname][] = $res[$i];                                 }                             } else {                                 $sordata[$childname][] = $res;                             }                         } else {                             $sordata[$childname] = $res;                         }                     }                     $new_data[] = $sordata;                 }             }         }     }     return $new_data; }

调用 deal_list_to_tree2 函数可以将一维数组转换为多维数组:

$multidimensionalData = deal_list_to_tree2($result);

现在,你将拥有一个包含所有子分类的多维数组。请注意,deal_list_to_tree2 函数是一个通用的函数,它可以用于转换任何一维数组到多维数组。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享