如何将新数据添加到JSON结构中?php在json树中添加新数据
这里是json.txt
的JSON:
[
{"name":"foo","number":"1"},
{"name":"bar","number":"2"},
{"name":"Hello","number":"3"}
]
现在我想添加一个新行{"name":"good day","number":"**"}
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newdata = array('name'=>'good day', 'number' => '**');// how to add `number` automatic `+1`, make it to `4` with php code?
$data[] = $newdata;
file_put_contents($file, json_encode($data));
你的代码看起来不错,你会得到什么输出? –
4因为它将是数组中的第四项,或者因为它是最大数(3)+1? – Yoshi
@Yoshi,如果我在这个'txt'中添加更多数据,以及如何自动添加数字? –