php将json数组合并为一个数组

noo*_*ook 5 php arrays merge json file

我试图循环一些json文件,并将它们组合成一个json文件.我的计划是拥有一个全局$allData数组,并将新的候选者合并到它们中.

<?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);  
Run Code Online (Sandbox Code Playgroud)

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

我想得到以下结果:

1.json:

{"date":"10"},{"comment":"some comment"},{"user":"john"}
Run Code Online (Sandbox Code Playgroud)

2.json:

{"date":"11"},{"comment":"another quote"},{"comment":"jim"}
Run Code Online (Sandbox Code Playgroud)

combined.json

[{"date":"10"},{"comment":"some comment"},{"user":"john"},
{"date":"11"},{"comment":"another quote"},{"comment":"jim"}]
Run Code Online (Sandbox Code Playgroud)

合并数组后,我只得到其中一个值.

[{"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"}]]
Run Code Online (Sandbox Code Playgroud)

jsz*_*ody 9

你的合并是奇怪的:

$result = array_merge($allData,$data);
Run Code Online (Sandbox Code Playgroud)

你想将每个新$data阵列合并到一个不断增长的$allData阵列上吗?我想你想这样做:

$allData = array_merge($allData,$data);
Run Code Online (Sandbox Code Playgroud)

你也可以摆脱这个,这是没有必要的.

if($count == 0){
    $allData = $data;
}
Run Code Online (Sandbox Code Playgroud)