我正在尝试为我的 React js 和 Laravel 创建一个 API 作为后端。因此,对于菜单,我有类别、子类别和进一步的子类别。我需要将所有结果合并如下,
{
"response": 200,
"data": [
{
"id": 15,
"name": "dfdfhdf rtuydf",
"slug": "dfdfhdf-rtuydf",
"subcategory": [
{
"sub_id": 15,
"sub_name": "dfdfhdf rtuydf",
"sub_slug": "dfdfhdf-rtuydf"
"fsubcategory": [
{
"fsub_id": 15,
"fsub_name": "dfdfhdf rtuydf",
"fsub_slug": "dfdfhdf-rtuydf"
},
...
]
},
...
]
},
....
]
}
我尝试使用下面的代码,但结果未按预期显示。
$list = Category::select('id', 'name', 'slug')->where(array('in_menu' => 1, 'status' => 1, 'deleted_at' => null))->orderBy('id', 'desc')->get();
$array = [];
foreach ($list as $category) {
$sublist = Subcategory::select('id', 'name', 'slug')->where(array('category_id' => $category->id, 'status' => 1, 'deleted_at' => null))->orderBy('id', 'desc')->get();
$first = array("id" => $category->id, "name" => $category->name, "slug" => $category->slug);
array_push($array, array("category" => $first));
foreach($sublist as $subcategory) {
array_push($array, array("subcategory" => array("sub_id" => $subcategory->id, "sub_name" => $subcategory->name, "sub_slug" => $subcategory->slug)));
}
}
return response()->json(['response' => 200, 'data' => $array]);
上述代码的结果是,
{
"response": 200,
"data": [
{
"category": {
"id": 15,
"name": "dfdfhdf rtuydf",
"slug": "dfdfhdf-rtuydf"
}
},
{
"subcategory": {
"sub_id": 6,
"sub_name": "Test Subcategory 221",
"sub_slug": "test-subcategory-221"
}
},
]
}
如何达到需要的结果。我真的被困在这里了。
牛魔王的故事