MySQL JOIN to JSON array
This is not vastly different but you might think its a little easier to read and follow and probably therefore debug.

With this code everything can be done within a single loop rather than the more complex multiple loop while/do that you originally used.

This also makes use of the stdClass provided by PHP to generate an array of objects as per your requirement, where your code was creating an array of arrays.

// get all the posts and their photos
$st = $db-&gt;prepare ('SELECT * FROM `posts` ' .
                    'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st-&gt;execute ();

// init our results array
$posts = array ();

$lastPostId = NULL;

// get the first post (plus it's JOINed photo)
while ( $post = $st-&gt;fetch (PDO::FETCH_OBJ) ) {

    if ( $lastPostId != $post-&gt;id ) {
        if ( $lastPostId !== NULL ) {
            // add this obj to the post array
            $posts[] = $tPost;
        }
        // start a new temp object
        $tPost          = stdClass();
        $tPost-&gt;id      = $post-&gt;id;
        $tPost-&gt;content = $post-&gt;content;
        $tPost-&gt;photos  = array();
    }

    // Add photo_id to current tPost obj
    $tPost-&gt;photos[] = $post-&gt;photo_id;

    $lastPostId = $post-&gt;id;
}

// and send it back
echo json_encode($posts);