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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With