user2810718 user2810718 - 2 months ago 14
JSON Question

Decode JSON post data

My php file receives a post from ajax call. The string received by the php file is as follows :


array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }


I am trying unsuccessfully to decode this string then loop through the values in the array. I have tried the following :

$myarray =json_decode($_POST["userid"],true);
foreach ($myarray as $value) {
//do something with value
}


I am not sure whether the decode is the issue or my syntax to loop through the PHP array.

Answer

The POST data you'd want to manipulate is stored in $_POST['userid]

In case you're trying to access this comma separated user ids, you need to convert this to an array first using explode(). And then loop through these id's.

if (isset($_POST)) {

   $user_ids = $_POST['userid'];  // assssssss,camo,castor

   $user_id_arr = explode(',', $user_ids);  // Converts string to array Array (0 => assssssss, 1 => camo, 2 => castor)

   foreach ($user_id_arr as $user_id) {
       //Statements
   } 
}