递归函数获取具有父子关系的嵌套项

Recursive function to get nested items with parent-child relations

我想从 Laravel 7 中的 MySQL table 中获取嵌套类别数据。

这是MySQL Table:

------------------------
|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     |
|---|------|-----------| 

我想要以下输出:

A
a
ab
bc
ca
B
b
2b
3b
C
c

我当前的代码(在控制器中)是:

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]);

}

当前输出:

A
a
ab
bc
ca

如您所见,它不会遍历 B 和 C。感谢任何帮助。

您在 foreach 循环中有一个 return 语句。

这会导致只处理第一个 category_id 的值,而不处理其他值。

您不应该直接return,而是将return值存储在一个数组中,例如在循环之后return。