I'm building a HTTP API and this part should return a JSON list of posts and their attached photos, like this:
[
{
"id": "788",
"content": "Foo bar! Foo foo, bar bar.",
"photos": [181, 282, 182]
},
...
]
And this is my PHP code handling the request:
// get all the posts and their photos
$st = $db->prepare ('SELECT * FROM `posts` ' .
'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st->execute ();
// init our results array
$posts = array ();
// get the first post (plus it's JOINed photo)
$row = $st->fetch (PDO::FETCH_OBJ);
// if there's more left
while (false !== $row) {
// init our post array
$post = array (
'id' => $row->id,
'content' => $row->content,
'photos' => array () // to fill with the photos
);
do {
// don't add a `null` if there's no photos
if (null !== $row->screenshot)
$post ['photos'] [] = $row->photo_id;
// get the row, repeat if it's another photo
} while (false !== ($row = $st->fetch (PDO::FETCH_OBJ)) &&
$row->id === $post ['id']);
// add this post to the list
$posts [] = $post;
}
// and send it back
echo json_encode ($posts);
Pretty simple JOIN
parsing job, right? But the code is anything but nice or simple!
How can I parse MySQL's JOIN
results elegantly into the JSON heirarchy that I need?