Let's assume I have the following database structure of car manufacturers and the corresponding cars:
manufacturers:
----------------------------------
| manufacturer | founded_in | id |
|--------------|------------|----|
| Daimler AG | 1927 | 1 |
| Volkswagen AG| 1937 | 2 |
----------------------------------
cars:
-------------------------------------
| car | built_in | manufacturer |
|---------|----------|---------------
| C Class | 1993 | 1 |
| E Class | 1993 | 1 |
| Golf | 1974 | 2 |
-------------------------------------
The id column of manufacturers is the primary key and the manufacturer column of cars has the corresponding foreign key constraint.
I'd like to produce the following JSON output using PHPs json_encode:
{
"manufacturers": {
"Daimler AG": {
"founded in": "1927",
"cars": [
"C Class",
"E Class"
]
},
"Volkswagen AG": {
"founded in": "1937",
"cars": [
"Golf"
]
}
}
}
To get the manufacturers and their founded_in I'd just perform:
SELECT manufacturer, founded_in FROM manufacturers
And fetch them to an array. How do I assign the cars correctly though, after making a second query?