我一直试图在两天的大部分时间里解决这个问题而没有成功。我正在尝试使用php组合/添加到存储在我的服务器上的.json文件中的json数组。
这是我尝试合并的简短版本。
box.json:
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}]
张贴了json:
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
这就是我需要的。
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
这就是我得到的。 (数组内的数组)
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]
这是我的代码:
<?php
$sentArray = $_POST['json'];
$boxArray = file_get_contents('ajax/box.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
$json = json_encode($sentdata);
$fsize = filesize('ajax/box.json');
if ($fsize <= 5000){
if (json_encode($json) != null) { /* sanity check */
$file = fopen('ajax/box.json' ,'w+');
fwrite($file, $json);
fclose($file);
}else{
/*rest of code*/
}
?>
请帮助我的理智开始受到质疑。
答案 0 :(得分:1)
这是你的问题
$sentdata[] = $getdata;
使用foreach
foreach($getdata as $value)
$sentdata[] = $value;
<强>更新强>
但我认为你需要$sentdata
而不是$getdata
foreach($senttdata as $value)
$getdata[] = $value;
然后将$getdata
添加到您的文件中。
答案 1 :(得分:1)
$box = json_decode(file_get_contents('ajax/box.json'));
$posted = json_decode($_POST['json']);
$merge = array_merge ((array)$box,(array)$posted);
如果$ box或$ posted变为null或false,则Casting(数组)会阻止错误,它将是一个空数组
答案 2 :(得分:0)
而不是:
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
尝试:
$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);
通过使用array_merge,您可以将数组合并为一个数组,而不是将一个数组作为值添加到另一个数组中。
请注意,我更改了结果数据的名称 - 尽量避免使用相同名称和不同大小写的变量,这样可以使事情更容易理解(对于您和将来支持代码的开发人员而言)。
干杯