我正试图将json数组合并在一起,我正在从json文件中读取一个数组,第二个是从变量值
创建的$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);
当我为用户1和用户2运行这段代码时,我得到了正确的结果:
[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"}]
但是当我再运行一次时,user1和user2变成了一个数组user3变成了第三个数组,像这样:
[[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"}],{"ID":"3","Username":"user3","Account":"12345"}]
我做错了什么?我期望一个数组有3个json对象,像这样:
[{"ID":"1","Username":"user1","Account":"123"},{"ID":"2","Username":"user2","Account":"1234"},{"ID":"3","Username":"user3","Account":"12345"}]
威胁主数组始终为索引数组:
$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);
现在每个新条目都被添加到顶级索引数组中。