【问题标题】:Multiple External JSON files to be merged要合并的多个外部 JSON 文件
【发布时间】:2016-05-27 10:44:57
【问题描述】:

我有大约 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 1 的示例:http://pastebin.com/QDyGGjQj

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

【问题讨论】:

  • 你可以在array_merge函数中给n个数组作为参数

标签: php arrays json merge


【解决方案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

【讨论】:

  • 当我尝试替换目录路径时很遗憾没有结果。
  • 虽然很高兴知道 array_chunk 方法存在,但遗憾的是,分块方法不是我需要的输出。我需要我提供的 json 示例保持相同的格式,但只附加下一个条目。这将使 Json [{0},{1},{2},{3},{4}] 一直到 50。然后数组将在这些之下。这样我就可以使用另一个工具一次导入 50 个游览。
  • 您能发布您的预期输出吗?
  • 这是一个手动合并 3 个 json 文件的示例。 pastebin.com/fP2MHN2Y 要查看,我建议复制到 jsonviewer.stack.hu,您会看到我希望该格式存在的方式。
  • 数组块对你有用。它只是给你一个额外的父数组。我认为这很好。你可以处理它。
【解决方案2】:

我不确定您究竟为什么要合并数组而不是制作数组数组,但我想类似于您正在寻找的东西可以通过这个来实现:

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

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

【讨论】:

  • 我正在合并以供导入使用。我将如何将 $files 定义为我的 json 文件,它会像 $files = $i 。 '.json';并在 for each 循环中有一个 $i?
  • 抱歉 @Sergey-Vidusov 结果似乎显示了 string(2) "[]"。
  • 您确定您使用的 JSON 文件路径正确吗?
  • 我将它们放在根目录下的测试文件夹中,因此我设置为 /test/
  • 在这种情况下,您可能需要仔细查看您传递到file_get_contents() 的确切位置,并查看它是否是有效的系统文件路径。我还在上面编辑了我的答案,以修复“。”中的错误变量名称。和“..”检查。
猜你喜欢
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
相关资源
最近更新 更多