foreach里面的静态数组

How can I replace the locations here with a foreach loop? When I put the foreach inside of the array, the code breaks. I guessing the answer has to do with creating a foreach variable and then entering that for the levels value instead?

This is my array

$data = array(
'name' => Locations,
'data' => '{
    "title":"USA",
    "location":"World",
    "levels":[
        {
            "id":"states",
            "title":"States",
            "locations":[
                {
                    "id":"ca",
                    "title":"California",
                    "pin":"hidden",
                    "x":"0.0718",
                    "y":"0.4546",
                },
                {
                    "id":"wa",
                    "title":"Washington",
                    "pin":"hidden",
                    "x":"0.1331",
                    "y":"0.0971"
                }
            ]
        }
    ]
}'

Here is my current foreach.

foreach ($response->records as $record) {
    $id = $record->Id;
    $title = $record->Title;
    $pin = $record->Pin;
    $x = $record->X;
    $y = $record->Y;

    echo {
        "id": $id,
        "title": $title,
        "pin": $pin,
        "x": $x,
        "y": $y
    }
}

Any help would be appreciated.

$arr = array();
foreach ($response->records as $record) {
    $r['id'] = $record->Id;
    $r['title'] = $record->Title;
    $r['pin'] = $record->Pin;
    $r['x'] = $record->X;
    $r['y'] = $record->Y;

    $arr[] = $r;
}

echo json_encode($arr);