【问题标题】:Append nested JSON array with php用 php 附加嵌套的 JSON 数组
【发布时间】:2012-12-27 17:00:34
【问题描述】:

我在一个文件中有一个嵌套的 json 数组,如下所示:

{
"id": 12345679,
"gid": 6012,
"history": [
    {
        "date": "0000-00-00 00:00:00",
        "rank": 6
    }
]}

我很好奇如何读取 json 文件并用 php 附加历史数组,然后重写名为 data.json 的文件。

这是我到目前为止所得到的。

$json = file_get_contents('data.json');
$json = (array)json_decode($json);
$output = $json['history'][] = array(
    array('date' => '0000-00-00 00:00:00', 'rank' => 3),
    array('date' => '0000-00-00 00:00:00', 'rank' => 2),
    array('date' => '0000-00-00 00:00:00', 'rank' => 6)
);

  $data = json_encode(array_marge($json, $output));

感谢您的帮助!

【问题讨论】:

    标签: php json multidimensional-array


    【解决方案1】:

    您当前正在附加一个包含三个子数组的块。你想要做的是单独出现:

    $json['history'][] = array('date' => '0000-00-00 00:00:00', 'rank' => 3);
    $json['history'][] = array('date' => '0000-00-00 00:00:00', 'rank' => 2);
    $json['history'][] = array('date' => '0000-00-00 00:00:00', 'rank' => 6);
    

    然后将其用作$output

    或者使用array_merge 将您的三项列表添加到输入$json["history"]。但不要像上次尝试的那样合并两个数组 $json$output

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多