2011-07-19 33 views
2

如何将新数据添加到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)); 
+0

你的代码看起来不错,你会得到什么输出? –

+0

4因为它将是数组中的第四项,或者因为它是最大数(3)+1? – Yoshi

+0

@Yoshi,如果我在这个'txt'中添加更多数据,以及如何自动添加数字? –

回答

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; 
+0

解析错误:语法错误,意想不到的T_FUNCTION,期待')第4行 –

+0

@fish man我假设你正在测试一个旧的PHP版本。用适用于php <5.3的代码更新了答案。 – phihag

+0

是的,低于5.3,我会立即更新并测试它。谢谢。 –

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)); 
?>