user2810718
user2810718

Reputation: 71

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.

Upvotes: 0

Views: 1120

Answers (3)

W3D3
W3D3

Reputation: 357

The string you have passed into your $_POST is not JSON, so json_decode will not work on some random comma seperated values.

You can either pass in real JSON, or just use the explode method of splitting these values:

// explode example
$users  = "assssssss,camo,castor";
$usersarray = explode(",", $users);

Upvotes: 0

Indrasis Datta
Indrasis Datta

Reputation: 8606

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

Upvotes: 1

Pranav Bhatt
Pranav Bhatt

Reputation: 745

$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. So when you decode with json_decode that will decode JSON string to Object/Array.

But in your scenario you have not passed JSON String to $_POST so it not looks decoding.

Upvotes: 0

Related Questions