Reputation: 77
I have around 850 json files and I'd like to merge them in groups of 50. What would the best method be for this?
array_merge ?
I've seen some examples but none with more than 2 arrays.
<?
$array1 = json_decode(file_get_contents('1.json'));
$array2 = json_decode(file_get_contents('2.json'));
$array3 = json_decode(file_get_contents('3.json'));
$array4 = json_decode(file_get_contents('4.json'));
$array5 = json_decode(file_get_contents('5.json'));
$array6 = json_decode(file_get_contents('6.json'));
$array7 = json_decode(file_get_contents('7.json'));
$array8 = json_decode(file_get_contents('8.json'));
$array9 = json_decode(file_get_contents('9.json'));
$array10 = json_decode(file_get_contents('10.json'));
$array11 = json_decode(file_get_contents('11.json'));
$array12 = json_decode(file_get_contents('12.json'));
$array13 = json_decode(file_get_contents('13.json'));
$array14 = json_decode(file_get_contents('14.json'));
$array15 = json_decode(file_get_contents('15.json'));
$result = array_merge($array14, $array15);
var_dump(json_encode($result));
?>
Example of 1 of the JSON: http://pastebin.com/QDyGGjQj
Hopeful Outcome (3 out of 50 since 50 is huge example): http://pastebin.com/fP2MHN2Y
Upvotes: 0
Views: 362
Reputation: 1342
I'm not sure why exactly you'd want to merge the arrays instead of making an array of arrays, but I guess something similar to what you're looking for can be achieved by this:
$path_to_your_files = '/path/to/your/json/files';
$result = array();
if ($handle = opendir($path_to_your_files)) {
while (false !== ($filename = readdir($handle))) {
if ($filename != "." && $filename != "..") {
$result = $result + json_decode(file_get_contents($path_to_your_files .'/'. $filename));
}
}
}
var_dump(json_encode($result));
EDIT: added the file system reader.
Upvotes: 1
Reputation: 3515
Try this :
$dir = = "/files/"; //replace it with yours.
$f = scandir($dir);
foreach($f as $file) {
$arr[] = json_decode(file_get_contents($file));
}
$chunk = array_chunk($arr,50);
After getting all the results in single array you can use array_chunk
.
Refer this : http://www.w3schools.com/php/func_array_chunk.asp
Upvotes: 1