php merge json arrays into one array
arrays, file, json, merge, php
Solution
Your merge is odd:
$result = array_merge($allData,$data);
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;
}
Problem
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"}]] ```