Listing blog posts, each of which may belong to multiple categories
I am not sure why you are using 2 foreach loops, you should be able to combine them.

foreach ($result as $value) {
    if(empty($resultMap[$value['id']])) {
        unset( $value['name'] );
        $resultMap[ $value['id'] ] = $value;
        $resultMap[$value['id']]['categories'] = array();
    }

    $resultMap[$value['id']]['categories'][] = array(
        'name' =&gt; $value['name'],
    );
}