Somewhat stupid question, I’m sure, bud I do need an answer.
I’m doing this short learning project where I need to get a database to output some JSON.
I do know how to structure tables, but due to my very short history with them, I’ve not figured out how to deal with an array of objects within a tablecell (in this example, the pointsOfInterest and events). Should I make separate tables for them and somehow leave a reference to the separate tables for each one? And how do I deal with them in php?
TL:DR; How should I structure my database to allow for JSON output like this?:
{id: 'oyafestivalen',
displayName: 'Øyafestivalen 2011',
description: 'Music festival in Middelalderparken, Oslo',
pointsOfInterest: [
{id: 'sjosiden',
displayName: 'Sjøsiden',
lat: 59.904453,
lng: 10.762905},
{id: 'vika',
displayName: 'Vika',
lat: 59.906086,
lng: 10.763276},
{type: 'wc', // type is optional, defaults to 'venue'
// displayName optional, not specified here
lat: 59.903625,
lng: 10.763276},
{type: 'firstaid',
lat: 59.903625,
lng: 10.763276},
{type: 'entrance',
lat: 59.903625,
lng: 10.763276},
{type: 'exit',
lat: 59.903625,
lng: 10.763276},
{type: 'camping',
lat: 59.903625,
lng: 10.763276},
{type: 'food',
displayName: 'Random restaurant name',
description: 'They serve good food. Vegetarian-friendly',
lat: 59.903625,
lng: 10.763276},
{type: 'drinks',
displayName: 'Random bar name',
lat: 59.903625,
lng: 10.763029}
],
events: [
{displayName: 'Kyuss Lives!',
venue: 'sjosiden',
startDateTime: '2011-08-13T19:30',
endDateTime: '2011-08-13T21:00',
tags: ['rock', 'stoner']},
{displayName: 'Givers',
description: 'Givers are an indie pop group from Lafayette, Louisiana. The band is made up of...',
venue: 'vika',
// Default one hour duration if no endTime
startDateTime: '2011-08-13T18:05',
tags: ['pop', 'indie']}
]
I can’t possibly tell you the structure of your tables nor can i tell you the exact queries you need to execute to get that output, but i can tell you this:
You can’t possibly produce such an output from an SQL query. However you can construct such an output with multiple queries and manipulate their output with PHP to construct your multi-dimension array. For example the content of pointsOfInterest should be a separate query. To help you get the desired output use
print_r()in PHP to check how your array is going. Once you get what you want, usejson_encode()to convert the array into a json string in PHP.