简体   繁体   English

php将json数组合并为一个数组

[英]php merge json arrays into one array

I am trying to loop through some json files, and combine them into one json file.我试图遍历一些 json 文件,并将它们组合成一个 json 文件。 My plan is to have a global $allData array, and just merge new candidates into them.我的计划是拥有一个全局$allData数组,并将新的候选者合并到其中。

<?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?如何将多个json文件合并为一个?

I would like the following result:我想要以下结果:

1.json: 1.json:

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

2.json: 2.json:

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

combined.json组合.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"}]]

Your merge is odd:你的合并很奇怪:

$result = array_merge($allData,$data);

You want to be merging each new $data array onto a growing $allData array right?您想将每个新的$data数组合并到一个不断增长的$allData数组中,对吗? 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;
}

As stated before, $result = array_merge($allData,$data);如前所述, $result = array_merge($allData,$data); is the best way to merge arrays.是合并数组的最佳方式。 This code works to merge the two, however, the problem was that my json was not properly formed.这段代码可以合并两者,但是,问题是我的 json 格式不正确。

I didn't have [] around my two files, so they could not be merged properly.我的两个文件周围没有[] ,因此无法正确合并它们。

我的解决方案很糟糕,但它有效:我用逗号替换字符串一的 },删除第二个字符串的 { 并连接这两个字符串......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM