Reputation: 25
I'm iterating over a directory and merging the JSON-Files in it. But it doesn't quite work as i want it to. The array I get after iterating over 3 files is just the last file. Somewhere along the way it seems to just overwrite the previous files. I'm not sure where though. Also I would like to remove rows with certain entries, but I'd be happy if the merging would work at least.
<?php
$dir = new DirectoryIterator("path1");
$destination = "path2";
$json = file_get_contents($destination);
$result = json_decode($json,true);
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$path = $dir -> getPathname();
$data = file_get_contents($path);
echo $data; //works as intended. Prints 3 different Arrays after eachother
$current = json_decode(file_get_contents($path),true);
$result = array_merge($result,$current);
}
}
$final = json_encode($result);
file_put_contents($destination,$final);
?>
Thanks in advance for any help
Upvotes: 2
Views: 264
Reputation: 350079
The function array_merge
has this overwriting behaviour, as specified in the manual:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
This effect can be illustrated with this little example:
$a1 = array("a" => 1, "b" => 2);
$a2 = array("a" => 100, "b" => 200);
$result = array_merge($a1, $a2);
print_r (json_encode($result));
output:
{"a":100,"b":200}
So, the values of the first array are lost.
There are several solutions, but it depends on which result you would like to get. If for instance you would like to get this:
{"a":[1, 100],"b":[2, 200]}
Then use the function array_merge_recursive
instead of array_merge
.
If you prefer to get this:
[{"a":1,"b":2},{"a":100,"b":200}]
Then use this code:
$result[] = $a1;
$result[] = $a2;
In your original code, that last solution would look like this:
$result[] = json_decode($json,true);
foreach ($dir as $fileinfo) {
// ...
$result[] = $current;
// ...
}
Upvotes: 1