简体   繁体   中英

php merge json arrays into one array

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"}]]

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;
}

As stated before, $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.

I didn't have [] around my two files, so they could not be merged properly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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