Home > Software engineering >  whats the right way to merge json objects in php?
whats the right way to merge json objects in php?

Time:12-19

I am trying to merge json arrays together , I am reading one array from the json file and second is created from the variable values

$b = json_encode(array("ID"=>$userid, "Username"=>$Username, "Account"=>$Account)); 
$filedata =file_get_contents("use.json",true);
$a = $filedata;  
$user[] = json_decode($a, true);
$user[] = json_decode($b, true);
$json_merge = json_encode($user); 
file_put_contents("use.json",$json_merge);

when I run this code for user 1 and user 2 , I get this which is correct :

[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"}]

But when I run it one more time , user1 and user2 become one array and user 3 becomes the 3rd array like this:

[[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"}],{"ID":"3","Username":"user3","Account":"12345"}]

What am I doing wrong ? I am expecting one array with 3 json objects like this :

[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"},{"ID":"3","Username":"user3","Account":"12345"}]

CodePudding user response:

Threat main array allways as indexed array:

$b = json_encode(array("ID"=>$userid, "Username"=>$Username, "Account"=>$Account)); 
#start with an empty "use.json"
$filedata = file_get_contents("use.json",true);
$a = $filedata;  
$user = json_decode($a, true);
if(!is_array($user)){# only for the first run with empty use.json
   $user = [];
}
$user[] = json_decode($b, true);#add new user 
$json_merge = json_encode($user); 
file_put_contents("use.json",$json_merge);

Now every new entry is added to the toplevel index array.

  • Related