ThinkPHP框架如何将递归获取的无限级分类子分类数据转化为多维数组?

在thinkphp框架中,我们可以通过递归的方式读取无限级分类的子分类。使用getchildarea()函数时,返回的是一维数组,如果您需要多维数组,可以采用以下方式改进:

function getchildarea($id){
    if(!$id){
        return;
    }
    static $area;
    $area = $area ?? new \app\common\model\area;
    $result = collection($area->where(['pid' => $id])->order('id desc')->select())->toarray();
    static $res = [];
    if($result){
        foreach ($result as $key => $val) {
            $val['children'] = getchildarea($val['id']); 
            $res[] = $val;
        }
    }
    return $res;
}

配合deal_list_to_tree2()方法,可以将一维数组转化为多维数组:

这样,返回的多维数组格式为:

[
  {
    "id": 1,
    "area_name": "安徽省",
    "pid": 0,
    "level": 1,
    "children": [
      {
        "id": 4,
        "area_name": "合肥市",
        "pid": 1,
        "level": 2,
        "children": [
          {
            "id": 7,
            "area_name": "肥东县",
            "pid": 4,
            "level": 3,
            "children": [
              {
                "id": 8,
                "area_name": "桃园镇",
                "pid": 7,
                "level": 4,
                "children": [
                  {
                    "id": 9,
                    "area_name": "八斗乡",
                    "pid": 8,
                    "level": 5
                  }
                ]
              },
              {
                "id": 10,
                "area_name": "长丰县",
                "pid": 4,
                "level": 3
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "area_name": "江苏省",
    "pid": 0,
    "level": 1
  },
  {
    "id": 3,
    "area_name": "江西省",
    "pid": 0,
    "level": 1,
    "children": [
      {
        "id": 5,
        "area_name": "南昌市",
        "pid": 3,
        "level": 2
      },
      {
        "id": 6,
        "area_name": "九江市",
        "pid": 3,
        "level": 2
      }
    ]
  }
]