数组内的json_encode变量

I am using json_encode to create an array from a foreach that I would like to place inside of a static array. I have loaded the json_encoded array into a variable. If I echo the variable, the data looks great. It's just when I enter the variable into the array, it doesn't work.

This is my foreach.

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

$arr[] = $r;

}

$locations = json_encode($arr);

And this is my static array where I have entered the $locations variable.

$data = array(
    'name' => Locations,
    'data' => '{
        "title":"USA",
        "location":"World",
        "levels":[
            {
                "id":"states",
                "title":"States",
                "locations":'$locations'
            }
        ]
    }'
);

This it the error that I am seeing.

Parse error: syntax error, unexpected '$locations' (T_VARIABLE), expecting ')'

I would appreciate the help, thank you.

The gizmo you're looking for is the concatenation operator which looks like this

.

It glues strings together.

$data = array(
    'name' => Locations,
    'data' => '{
        "title":"USA",
        "location":"World",
        "levels":[
            {
                "id":"states",
                "title":"States",
                "locations":' . $locations . '
            }
        ]
    }'
); 

If ı true understood your think, encode the $locations variable to JsonString

json_encode($locations)

before add $data['data'] elm.

$data = array(
    'name' => Locations,
    'data' => '{
        "title":"USA",
        "location":"World",
        "levels":[
            {
                "id":"states",
                "title":"States",
                "locations":' . json_encode($locations) . '
            }
        ]
    }'
);