Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Javascript Object into PHP array [duplicate]

I send this Javascript array into PHP page using form submit {"1":"2","2":"2","3":"2","4":"2"}

Now, I want to convert this array into PHP array, like this

$cars = array("Volvo", "BMW", "Toyota");

So, this is what I tried:

$phparray = str_replace(':', ',', $_POST["questionandanswers"]); // Remove : and replace it with ,
$phparray = str_replace('}', '', $phparray); // Remove }
$phparray = str_replace('{', '', $phparray); // Remove {
echo '<br/>';
echo $phparray; // Output of this is: "1","2","2","2","3","2","4","2"



$questionandanswers = array($phparray); // Now convert it into PHP array

But it is not working. Looks like i cannot put $phparray variable here array($phparray)

But, If instead of putting $phparray variable in array($phparray), If i put the output of $phparray manually, then, it works like: array("1","2","2","2","3","2","4","2")

What's the solution?

like image 463
Josh Poor Avatar asked Oct 07 '17 08:10

Josh Poor


2 Answers

It seems that your form submits a json object to the server so use json_decode with second parameter set to true to convert it to an array.

$php_array=  json_decode($_POST["questionandanswers"],true)
like image 148
Osama Avatar answered Nov 19 '22 17:11

Osama


Use json_decode like json_decode($json). It will return an object. If you want array, use json_decode($json, true). See: http://sg2.php.net/manual/en/function.json-decode.php

like image 1
Arka Roy Avatar answered Nov 19 '22 19:11

Arka Roy