I have the following MySQL table:
+----+----------+--------+------+
| id | brand | model | year |
+----+----------+--------+------+
| 1 | audi | tt | 2014 |
+----+----------+--------+------+
| 2 | audi | a4 | 2015 |
+----+----------+--------+------+
| 3 | mercedes | aclass | 2014 |
+----+----------+--------+------+
| 4 | mercedes | cclass | 2017 |
+----+----------+--------+------+
I am using MYSQL in PHP and writing a query to get this data:
$carsQuery = SELECT * FROM cars_table ORDER BY model ASC;
After the query is executed I am using PHP to try an achieve the following JSON Object output:
{
"car_models": [
{
"id": "audi",
"name": "Audi",
"cars": [
{
"id": "1",
"model": "tt",
"year": "2014",
"brand": "audi"
},
{
"id": "2",
"model": "a4",
"year": "2015",
"brand": "audi"
}
]
},
{
"id": "mercedes",
"name": "Mercedes",
"cars": [
{
"id": "3",
"model": "aclass",
"year": "2014",
"brand": "mercedes"
},
{
"id": "4",
"model": "cclass",
"year": "2017",
"brand": "mercedes"
}
]
}
]
}
The following snippet is the PHP code I am using to achieve this:
foreach($carsQuery as $carQuery){
$cars[$carQuery->brand][] = $carQuery;
}
return array(
'car_models' => $carQuery
);
The result is being grouped however I cannot get to the point of adding the other fields in order to achieve the JSON object I want.