我正试图调用array_push,将通过GET请求发送的数据添加到我的json数组中,该数组保存我的GCM客户端的注册ID
<?php
//read current regids
$myfile = fopen("regids.json", "r") or die("Unable to open file!");
$current_regids = fread($myfile,filesize("regids.json"));
// decode json
$decoded_json= json_decode($current_regids);
//save to php format array
$array = array($decoded_json);
//close file
fclose($myfile);
//get registration id
$regid = $_GET["regid"];
//push new reg id into array
array_push($array,$regid);
echo json_encode($array);
?>
JSON应该如下
["regid1","regid2", "regid3","regid4"]
然而,当我运行它的代码以排列_推送"regid5"时,它会给我这个
[["regid1","regid2","regid3","regid4"],"regid5"]
这是一个主要的头痛
解码时已经得到一个数组:
// decode json
$decoded_json= json_decode($current_regids);
// now you have an array or object, depending on the input
// in your case it seems to be an array
然后将结果放入另一个数组:
//save to php format array
$array = array($decoded_json);
现在有了一个嵌套数组。
您需要删除此行/使用$decoded_json
作为要操作的数组:
$array = array($decoded_json);
注意:-如果使用array_push()
向数组添加一个元素,则最好使用$array[] = "value"
,因为这样就没有调用函数的开销,而且它也比array_push()
更快、更安全。