将json数组添加/组合到json文件php中的数组

将json数组添加/组合到json文件php中的数组,php,json,array-push,Php,Json,Array Push,两天来,我一直在努力解决这个问题,但都没有成功。我正在尝试使用php合并/添加到存储在服务器上的.json文件中的json数组中 这是我试图结合的内容的简短版本。 [{"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"}] box

两天来,我一直在努力解决这个问题,但都没有成功。我正在尝试使用php合并/添加到存储在服务器上的.json文件中的json数组中

这是我试图结合的内容的简短版本。

[{"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"}]
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"}]
这就是我得到的。(数组中的数组)

这是我的代码:

<?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*/
}
?>

请帮助我,我的理智开始受到质疑。

这是你的问题

$sentdata[] = $getdata; 
使用
foreach

foreach($getdata as $value)
    $sentdata[] = $value;
更新: 但是我想你需要这个来
$sentdata
而不是
$getdata

foreach($senttdata as $value)
    $getdata[] = $value;
然后将
$getdata
放入您的文件。

而不是:

$sentdata[] = $getdata;   /* I also tried array_push($sentdata, $getdata); */
尝试:

通过使用,您可以将数组合并到一个数组中,而不是将一个数组作为值添加到另一个数组中

请注意,我更改了结果数据的名称-尽量避免使用相同名称和不同大小写的变量,这将使事情更容易理解(对于您和支持您的代码的未来开发人员而言)

干杯


强制转换(数组)防止错误如果$box或$posted变为null或false,它将是一个空数组

迭代不是最佳答案-根据数据集的大小,这可能会变得非常昂贵。@Madbreaks还有其他方法吗?
array\u merge
到底做什么?只要写一个名字,你的代码就是最好的?这个函数到底做什么?我解释了array\u merge的作用。我还提供了官方PHP文档的链接。这还不够吗?数据集将以5kb的速度写入,这会是一个问题吗?它将非常低效-这就是所谓的暴力解决方案。我需要添加值,它应该允许重复。你说得对,我的命名方法很混乱。我是一个学习发展的设计师。谢谢你的建议。尼克,它允许重复,因为你使用的是对象作为值,而不是标量。如果不清楚如何使用,请告诉我。我不久前试过运行array merge,但它不起作用(我一定是做错了什么),但看起来你是对的,它现在起作用了。谢谢
$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);
$box = json_decode(file_get_contents('ajax/box.json'));
$posted = json_decode($_POST['json']);
$merge = array_merge ((array)$box,(array)$posted);