要合并的多个外部JSON文件

时间:2016-02-16 08:47:22

标签: php arrays json merge

我有大约850个json文件,我想将它们合并为50个组。 对此最好的方法是什么?

array_merge?

我见过一些例子,但没有超过2个数组。

<?

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

?>

JSON中的一个示例:http://pastebin.com/QDyGGjQj

希望结果(自50以来50分中有3分是一个很好的例子): http://pastebin.com/fP2MHN2Y

2 个答案:

答案 0 :(得分:1)

我不确定为什么你想要合并数组而不是制作一个数组数组,但是我觉得类似于你想要的东西可以通过这个来实现:

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

编辑:添加了文件系统阅读器。

答案 1 :(得分:1)

试试这个:

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

在单个数组中获得所有结果后,您可以使用array_chunk

请参阅:http://www.w3schools.com/php/func_array_chunk.asp