API:获取无限极数,支持对parent_id(父级ID,最小0)和level(表示获取到第几层,最小1)的筛选
public function classificationSimple(Request $request)
{
$this->validate($request, [
'parent_id' => 'filled|integer',
'level' => 'filled|integer',
]);
$data = Classification::select('id', 'name_sc', 'name_en_us', 'parent_id', 'current_level')->get();
$tree = $this->getTree($data, $request->parent_id, $request->level);
return $this->responseSuccessWithExtrasAndMessage($tree);
//return $this->responseSuccessWithExtrasAndMessage(SimpleClassificationResource::collection($data1)->resource);
}
public function getTree($data, $parent_id = 0, $level = null)
{
$list = [];
foreach ($data as $key => $val) {
if ($val['parent_id'] == $parent_id) {
if (null == $level) {
$val['children'] = $this->getTree($data, $val['id'], $level);
$list[] = $val;
} elseif ($val['current_level'] <= $level) {
$val['children'] = $this->getTree($data, $val['id'], $level);
$list[] = $val;
}
}
}
return $list;
}
结果示例:
{
"code": "0",
"message": "Success",
"data": [
{
"id": 1,
"name_sc": "艺人",
"name_en_us": "Talent",
"parent_id": 0,
"current_level": 1,
"children": [
{
"id": 5,
"name_sc": "职业",
"name_en_us": "Occupation",
"parent_id": 1,
"current_level": 2,
"children": [
{
"id": 11,
"name_sc": "演员",
"name_en_us": "Actor/Actress",
"parent_id": 5,
"current_level": 3,
"children": []
}
]
},
{
"id": 6,
"name_sc": "地区",
"name_en_us": "Region",
"parent_id": 1,
"current_level": 2,
"children": [
{
"id": 12,
"name_sc": "中国内地",
"name_en_us": "China-Mainland",
"parent_id": 6,
"current_level": 3,
"children": []
}
]
}
]
},
{
"id": 2,
"name_sc": "连续剧",
"name_en_us": "Drama",
"parent_id": 0,
"current_level": 1,
"children": [
{
"id": 7,
"name_sc": "分类",
"name_en_us": "Genre",
"parent_id": 2,
"current_level": 2,
"children": [
{
"id": 13,
"name_sc": "默认",
"name_en_us": "Default",
"parent_id": 7,
"current_level": 3,
"children": []
}
]
}
]
},
{
"id": 3,
"name_sc": "动漫",
"name_en_us": "Anime",
"parent_id": 0,
"current_level": 1,
"children": [
{
"id": 8,
"name_sc": "分类",
"name_en_us": "Genre",
"parent_id": 3,
"current_level": 2,
"children": [
{
"id": 14,
"name_sc": "默认",
"name_en_us": "Default",
"parent_id": 8,
"current_level": 3,
"children": []
}
]
}
]
},
{
"id": 4,
"name_sc": "综艺节目",
"name_en_us": "Variety Show",
"parent_id": 0,
"current_level": 1,
"children": [
{
"id": 9,
"name_sc": "分类",
"name_en_us": "Genre",
"parent_id": 4,
"current_level": 2,
"children": [
{
"id": 15,
"name_sc": "默认",
"name_en_us": "Default",
"parent_id": 9,
"current_level": 3,
"children": []
}
]
},
{
"id": 10,
"name_sc": "角色",
"name_en_us": "Role",
"parent_id": 4,
"current_level": 2,
"children": [
{
"id": 16,
"name_sc": "默认",
"name_en_us": "Default",
"parent_id": 10,
"current_level": 3,
"children": [
{
"id": 17,
"name_sc": "rtt",
"name_en_us": "ff",
"parent_id": 16,
"current_level": 4,
"children": []
}
]
}
]
}
]
}
]
}
Post Views:
187