如何将新数据添加到 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));
最佳答案
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newNumber = max(array_map(
function($e) {return intval($e['number']);},
$data)) + 1;
$newdata = array('name'=>'good day', 'number' => strval($newNumber));
$data[] = $newdata;
file_put_contents($file, json_encode($data));
在 php < 5.3 中,将 $newNumber =
语句替换为:
$newNumber = max(array_map(
create_function('$e', 'return intval($e["number"]);'),
$data)) + 1;
关于php 在 json 树中添加新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6752365/