如何将新数据添加到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));
答案 0 :(得分:2)
$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;
答案 1 :(得分:1)
在您的示例中,数字是连续的。为什么不使用end
使号码自动增加?
<?php
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$number = (end($data)->number) + 1;
$newdata = array('name'=>'good day', 'number' => ''.$number.''); // how to add `number` automatic `+1`, make it to `4` with php code?
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>