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?