2015-04-06 96 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