简体   繁体   中英

Merge two JSON array in PHP

I need to merge two json file in PHP . One is at first empty, and the other one changes at each call.

I found a lot of codes to merge two JSON array into one in PHP but it doesn't work for me.

$final_array = array();
$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");


if(json_decode($first_json,true) == null){
    $final_array[] = json_decode($second_json,true);
    $merge_final_array = json_encode(json_decode($second_json,true));
}else{
    $final_array[] = json_decode($first_json,true);
    $final_array[] = json_decode($second_json,true);
    $merge_final_array = json_encode($final_array);
}

file_put_contents("test3.json", $merge_final_array);
$merge_final_array = null;

I add recursively to the "test3.json" file the data that I find in the "my-file.json".

This should give me :

[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true},{"win":true,"score":"Finish","device":"Android SDK built for x86"},{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

As it gives me:

[[[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true}],{"win":true,"score":"Finish","device":"Android SDK built for x86"}],{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

I also tried the method json_encode(array_merge(json_decode($first_json, true),json_decode($second_json, true))) It gives me this : Code + result

What did I do wrong?

You first need to convert your JSON to arrays before you can do anything with it in PHP .

First you need to create a new empty array in PHP and add the JSON arrays to that empty array.
Then encode the array again to JSON and write it to a file.
Your full code:

$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");

$first_array = json_decode($first_json, true); // make array of json
$second_array = json_decode($second_json, true); // make array of json

$final_array = array(); // create an empty array 
$final_array[] = $first_array; // add first array to empty array
$final_array[] = $second_array;  // add second array to array

$final_json = json_encode($final_array); // make a json from the array again

file_put_contents("test3.json", $final_json); // put the json inside a new file 

Here is what you want:

<?php

$finalArray = [];

// file_get_contents("test3.json");
$firstFileContent = '{"score":15,"win":true,"device":"Android SDK built for x86"}';

// file_get_contents("my-file.json")
$secondFileContent = '{"score":"Finish","device":"Android SDK built for x86","win":true}';

$firstJson = json_decode($firstFileContent, true);
if(JSON_ERROR_NONE === json_last_error()){
    $finalArray[] = $firstJson;
}

$finalArray[] = json_decode($secondFileContent, true);

$finalJson = json_encode($finalArray);

http://sandbox.onlinephpfunctions.com/code/404972fb59b4f7323f81ee444a1cb14f772f7748

It gives me this : Code + result

It's all because of you do array_merge of two arrays and second one will rewrite the first values. You should add second array to the result array, not merge.

array_merge(["a" => 1], ["a" => 2]) // result: ["a" => 2]

$result[] = ["a" => 1];
$result[] = ["a" => 2];
// result: [["a" => 1], ["a" => 2]]

json_encode(array_merge(json_decode($first_json, true),json_decode($second_json, true)))

This will not work, because in each file you have encoded object , not array of objects. If you have in first file {"a":1} and in second file {"a":2} , when you'd merge their decoded values the result will be {"a":2} , but if you'd edit them to [{"a": 1}] and [{"a": 2}] , the the result will be [{"a": 1}, {"a": 2}] because now you to merge the array of objects converted to array, not objects.


If you want to add the data from both files recursively, you should do something like this:

<?php

$finalArray = [];

$firstFileContent = '[[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true}],{"win":true,"score":"Finish","device":"Android SDK built for x86"}]';
$secondFileContent = '{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}';

mergeJsonRecursively($finalArray, $firstFileContent);
mergeJsonRecursively($finalArray, $secondFileContent);

function mergeJsonRecursively(array &$result, string $json)
{
    $decodedJson = json_decode($json);
    if (JSON_ERROR_NONE === json_last_error()) {
        tryToAddElementToResult($result, $decodedJson);

        if (is_array($decodedJson)) {
            foreach ($decodedJson as $element) {
                tryToAddElementToResult($result, $element);

                if (is_array($element)) {
                    mergeJsonRecursively($result, json_encode($element));
                }
            }
        }
    }
}

function tryToAddElementToResult(array &$result, $element)
{
    if (is_object($element)) {
        $result[] = json_decode(json_encode($element), true);
    }
}

$finalJson = json_encode($finalArray);

http://sandbox.onlinephpfunctions.com/code/f4858bcc87da34e4ee6639b2ee96c7ac3244ae1b

And you will give expected result:

[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true},{"win":true,"score":"Finish","device":"Android SDK built for x86"},{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

Just simply do this. You can add you own Error handling but the basic should be like :

$final_array = array();
$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");

$first_array = json_decode($first_json,true);
$second_array = json_decode($second_json,true);

if(is_array($first_array) and is_array(second_array)){
    $final_array = array_merge(first_array,second_array);
}
else if(!empty($first_array) and is_array($first_array)){
    $final_array = $first_array;
}
else if(!empty(second_array) and is_array(second_array)){
    $final_array = second_array;
}

$final_json = json_encode(final_array);

file_put_contents("test3.json", final_json);

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