laravel递归显示数组

显示的效果如下

```
{
"data":[
{
"id":115,
"brand_id":15,
"catalog_name":"\u603b\u76d1",
"parent_id":0,
"sort":-2,
"created_at":"2022-10-15T08:04:42.000000Z",
"updated_at":"2022-10-18T09:53:56.000000Z",
"children":[
{
"id":128,
"brand_id":15,
"catalog_name":"asdf",
"parent_id":115,
"sort":1,
"created_at":"2022-10-28T06:01:46.000000Z",
"updated_at":"2022-10-28T06:01:46.000000Z",
"children":[
{
"id":129,
"brand_id":15,
"catalog_name":"asdf1",
"parent_id":128,
"sort":1,
"created_at":"2022-10-28T06:01:51.000000Z",
"updated_at":"2022-10-28T06:01:51.000000Z"
}
]
}
]
},
{
"id":113,
"brand_id":15,
"catalog_name":"\u670d\u52a1",
"parent_id":0,
"sort":-1,
"created_at":"2022-10-13T07:58:03.000000Z",
"updated_at":"2022-10-18T09:53:56.000000Z"
},
{
"id":117,
"brand_id":15,
"catalog_name":"\u4e3b\u7ba1",
"parent_id":0,
"sort":0,
"created_at":"2022-10-15T08:04:43.000000Z",
"updated_at":"2022-10-18T09:54:06.000000Z"
}
],
"request_id":"6374c60a8f4c8",
"status":"success"
}
```

以下为controller方法

```
public function list(Request $request)
{
$result = CatalogService::getTree($request);
return $this->jsonData($result);
}
```

以下为service方法
```
/*
* 获取目录树
*/
public static function getTree($params){
$CatalogModel= new Catalog();
$list = $CatalogModel->where('brand_id',$params['brand_id'])->orderBy('sort', 'asc')->orderBy('updated_at','desc')->get();
if (!empty($list)) {
$list = $list->toArray();
$list = self::tree($list, ['id' => 0]);
return $list['children'] ?? [];
}
return [];
}

//树递归
public static function tree($list, $parent)
{
foreach ($list as $k => $item) {
if ($item['parent_id'] == $parent['id']) {
$parent['children'][] = self::tree($list, $item);
}
}
//跳出
return $parent;
}
```

数据库表结构

```
CREATE TABLE `hl_catalog` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`brand_id` int DEFAULT NULL COMMENT '关联业态ID',
`catalog_name` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '目录名称',
`parent_id` bigint NOT NULL COMMENT '父级目录id',
`sort` mediumint NOT NULL DEFAULT '0' COMMENT '排序:越小越往前排',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=130 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

访问url`https://www.test.com/api/v2/catalog/list?page=1&per_page=10&brand_id=15`

    A+
发布日期:2022年11月16日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: