💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
Laravel框架方式: ``` // 控制器 /** * 列表 */ public function infiniteGrading() { $list = $this->model->where('parent_id', 0) ->with('children')->get(); return $this->success($list); } // 模型 /** * 列表,所有子分级 * @return mixed */ public function children() { return $this->child()->with( 'children' ); } /** * 列表,子分级 * @return mixed */ public function child() { return $this->hasMany(get_class($this), 'parent_id' ,'id'); } ``` PHP代码方式: ``` /** * 无限分级列表 */ public function infiniteGrading() { $list = $this->model->get(); $menus = []; foreach($list as $key => $item) { if($item['parent_id'] == 0) { $menus[] = $item; unset($list[$key]); } } if(count($list) != 0 && count($menus) != 0) { $menus = $this->menusForeach($list, $menus, $menus); } return $this->success($menus); } /** * 无限分级算法 */ public function menusForeach($list, $menus, $menuLevel = []) { $children = []; $menuTem = []; foreach($menuLevel as $key => $menu) { foreach($list as $key1 => $item) { if($item['parent_id'] == $menu['id']) { array_push($children, $item); $menu['children'] = $children; unset($list[$key1]); $menuTem[] = $item; } } } if(count($list) != 0 && count($menuTem) != 0) { $menus = $this->menusForeach($list, $menus, $menuTem); } return $menus; } ```