2015-04-06 162 views
1

我试图打电话array_push添加通过GET请求我的JSON数组保存注册ID为我的GCM客户端发送的数据以JSON数组添加对象与PHP

<?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"] 

然而,当我运行的代码就序,以array_push “regid5” 它给了我这个

 [["regid1","regid2","regid3","regid4"],"regid5"] 

和它的一个大难题

回答

1

当你解码它你已经得到一个数组:

// 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); 
+0

哇,我觉得很愚蠢 – silberbaum 2015-04-06 09:17:22

+0

@harry_porter那么,这是周一早上,至少我在哪里;-) – jeroen 2015-04-06 09:18:48

1

注: -如果使用array_push()一个元素添加到阵列中,最好使用$array[] = "value"因为这样就没有调用函数的开销,它也比array_push()更快更安全。

+0

谢谢我的男人 – silberbaum 2015-04-06 09:24:45