Look my existing code:
class CategoryController extends ApiController
{
public function getCategory(){
$categories = DB::table('products')
->select('category', 'category_name')
->distinct('category', 'category_name')
->get();
$newArr = [];
foreach ($categories as $value) {
$newArr[$value->category_name] = [];
$subcategories = DB::table('products')
->select('subcategory_name')
->where('subcategory', 'LIKE', '%'. $value->category.'%')
->distinct('subcategory')
->get()->pluck('subcategory_name');
array_push($newArr[$value->category_name], $subcategories);
}
return response()->json([
'data' => $newArr
]);
}
}
The response seems:
"data": {
"Food": [
[
"Chicken",
"Egg",
"Pie"
]
],
"Drinks": [
[
"Beer",
"Juice",
"Water"
]
],
But this is not response what I want. I need like a:
data: {
{
category_name : "Food",
subcategories_name : ["Chicken", "Eggs", "Pie"]
}
{
category_name : "Drinks",
subcategories_name : ["Beer", "Juice", "Water"]
}
}
if you do not understand some part of the code ask me. I have fields in the products table like a category, category_name, subcategory, subcategory_name. The code category and subcategory it belongs to are the same code. All I need is to write a response as I wrote above. my logic was to put all categories into categories and in subcategories, I set up all subcategories and then merge them into one array. It does not matter to me how it will look like this, only the result is important. Thank.
ps. I do not know how important my database is for you, but there is a table of products and 4 fields = category, subcategory, category_name, subcategory_name. This is all.