php 在 json 树中添加新数据

标签 php json

如何将新数据添加到 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/

相关文章:

php - Laravel 5 View语法错误

c# - 如何处理 DateTime 的 JSON 数据成员中的空值

json - 使用 Go 的 json.Marshal 和 json.MarshalIndent 有什么区别?

php - 如何对json字符串进行排序?

javascript - 阻止人们通过导航到其他地方来绕过我的表单验证

javascript - 从 xml 文件创建 html5 播放列表

php - 具有定期付款的 Paypal Payments Advanced/Pro Layout C?

java - 正则表达式包含一个或多个电话号码

json - 自定义 Json 编码(marshal)处理

ios - 响应 : unauthorized (401) 的 AFNetworking 问题