PHP将JSON数组合并为一个数组

问题描述:

我正在尝试遍历一些json文件,并将它们组合成一个json文件.我的计划是拥有一个全局$allData数组,然后将新的候选者合并到其中.

I am trying to loop through some json files, and combine them into one json file. My plan is to have a global $allData array, and just merge new candidates into them.

<?php
$allData = array();
$count = 0;
if ($handle = opendir('./json/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {

            echo $entry."<br />";

            $source_file = file_get_contents('./json/'.$entry);

            $data = json_decode($source_file,TRUE);

            if($data != null){


                $allData = array_merge($allData,$data);
                echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />";
                print_r($allData);

            }
            else{
                echo "Invalid Json File";
            } //end else            
        }
closedir($handle);
}

echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />";

print_r($allData);  

但是,合并覆盖了文件.如何将多个json文件合并为一个?

However, the merge is overwriting the file. How can I combine multiple json files into one?

我想要以下结果:

1.json:

{"date":"10"},{"comment":"some comment"},{"user":"john"}

2.json:

{"date":"11"},{"comment":"another quote"},{"comment":"jim"}

combined.json

combined.json

[{"date":"10"},{"comment":"some comment"},{"user":"john"},
{"date":"11"},{"comment":"another quote"},{"comment":"jim"}]

合并数组后,我只会得到这些值之一.

I am only getting one of these values after I merge the arrays.

[{"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"}]]

您的合并很奇怪:

$result = array_merge($allData,$data);

您想将每个新的$data数组合并到一个不断增长的$allData数组中,对吗?我想您想改成这样:

You want to be merging each new $data array onto a growing $allData array right? I think you want to do this instead:

$allData = array_merge($allData,$data);

您也可以摆脱它,这不是必需的.

Also you can get rid of this, it's not necessary.

if($count == 0){
    $allData = $data;
}