我想從 Laravel 7 中的 MySQL 表中獲取嵌套類別數據。這是 MySQL 表:------------------------|id | name | parent_id ||---|------|-----------|| 1 | A | NULL ||---|------|-----------|| 2 | B | NULL ||---|------|-----------|| 3 | C | NULL ||---|------|-----------|| 4 | a | 1 ||---|------|-----------|| 5 | ab | 4 ||---|------|-----------|| 6 | bc | 4 ||---|------|-----------|| 7 | ca | 4 ||---|------|-----------|| 8 | b | 2 ||---|------|-----------|| 9 | 2b | 8 ||---|------|-----------||10 | 3b | 8 ||---|------|-----------||11 | c | 3 ||---|------|-----------| 我想要以下輸出:AaabbccaBb2b3bCc我當前的代碼(在控制器中)是:public function sort_category($data, $opt){ $contents = Category::where('category_id', $data)->get(); foreach($contents as $c){ $opt .= "<option value='".$c->id."'>".$c->name."</option>"; $count = Category::where('category_id', $c->id)->count(); if($count > 0){ return $this->sort_category($c->id, $opt); } } return $opt;}public function add_category_form(){ $opt = ''; $html = $this->sort_category(NULL, $opt); return view('admin.add_category', ['categories' => $html]);}電流輸出:Aaabbcca正如您所看到的,它不會迭代 B 和 C。任何幫助都會受到贊賞。
1 回答

蠱毒傳說
TA貢獻1895條經驗 獲得超3個贊
foreach 循環中有一個 return 語句。
這會導致僅category_id
處理第一個值,而不處理其他值。
您不應該直接返回,而是將返回值存儲在例如數組中,然后在循環之后返回。
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消