json_encode 数组中的变量

json_encode variable inside array

我正在使用 json_encode 从我想放置在静态数组中的 foreach 创建数组。我已经将 json_encoded 数组加载到一个变量中。如果我回显变量,数据看起来很棒。只是当我把变量输入到数组中时,它不起作用。

这是我的 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);

这是我输入 $locations 变量的静态数组。

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

这是我看到的错误。

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

非常感谢您的帮助,谢谢。

您要查找的小发明是 concatenation operator,它看起来像这样

.

它将字符串粘合在一起。

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

如果我真的理解你的想法,请将 $locations 变量编码为 JsonString

json_encode($locations)

在添加 $data['data'] 榆树之前。

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