使用键值创建JSON

时间:2014-12-22 16:21:13

标签: php json

所以我想要一个看起来像这样的JSON字符串:

{"Madagascar": [
    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    },
]}

但我的php脚本只输出键/值,如:

    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }

如何在PHP中设置“马达加斯加”键?

编辑:我尝试了如下:

$post_filter = $_POST['time']; //seconds
$filter = new DateTime(date("Y-m-d H:i:s"));
$filter_ = $filter->modify("-$post_filter second");
$insert = "SELECT * FROM chat "
        . "WHERE date >='" . $filter_->format('Y-m-d H:i:s') . "'"
        . "ORDER BY date DESC";
$return = $sql->return_array($insert);
foreach ($return as $var) {
    array_merge($arr, array($var["id"] => $var));
}
echo json_encode($arr);

1 个答案:

答案 0 :(得分:2)

轻松完成,这是一个例子。

$myInnerArray = [
    "year"=>2000, 
    "country"=>"Madagascar, 
    "country_id":847, 
    "indicator":"Net Income - National Currency (millions)"
];
$outerArray = ["Madagascar=>$myInnerArray];
echo json_encode($outerArray);

在新代码中,更改:

foreach ($return as $var) {
    array_merge($arr, array($var["id"] => $var));
}

要:

foreach ($return as $var) {
    $arr[$var["id"]] = $var;
}

为每一行分配一个元素。