php merge json arrays into one array

Viewed 20576

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

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

I would like the following result:

1.json:

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

2.json:

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

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"}]]
3 Answers

My solution is a bad one but it works: I replace the } of string one with a comma, remove the { of the second string and concatenate those two strings...

Related