使用PHP将对象添加到JSON数组
我试图调用array_push,将通过GET请求发送的数据添加到我的json数组中,该数组保存我的GCM客户端的注册ID使用PHP将对象添加到JSON数组,php,json,Php,Json,我试图调用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 $decode
<?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);
?>
然而,当我运行代码时,为了数组_push“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\u json
作为要操作的数组:
$array = array($decoded_json);
注意:-如果您使用
array\u push()
向数组添加一个元素,最好使用$array[]=“value”
,因为这样调用函数就没有开销,而且比array\u push()
@harry\u porter毕竟现在是星期一早上,至少在我现在的位置;-)
$array = array($decoded_json);