1

I am trying to call array_push to add data sent via a GET request to my json array that holds registration ids for my GCM Clients

<?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);

    ?>

The JSON should be as follows

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

However when I run the code it inorder to array_push "regid5" it gives me this

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

Its a major headache

0

2 Answers 2

1

You already get an array when you decode it:

// 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

And then you put the result in another array:

//save to php format array
$array =  array($decoded_json);

So now you have a nested array.

You need to remove this line / use $decoded_json as the array you want to manipulate:

$array =  array($decoded_json);
Sign up to request clarification or add additional context in comments.

Comments

1

Note:- If you use array_push() to add one element to the array it's better to use $array[] = "value" because in that way there is no overhead of calling a function and it is also much faster and safer than array_push().

Comments