2013-01-13 148 views
2

我有看起来像这样的文件的嵌套JSON数组:追加嵌套的JSON数组用PHP

{ 
"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)); 

感谢您的帮助!

回答

0

您目前正在追加一个由三个子阵列组成的块。你想要做的是每个单独的申请:

$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