6

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?

Josh Poor
  • 505
  • 1
  • 5
  • 12

2 Answers2

7

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)
Osama
  • 2,912
  • 1
  • 12
  • 15
  • Thanks, but the thing here is, the object name is not always in a serial order: It can also be like `Array ( [3] => 0 [6] => 0 [7] => 0 [11] => 0 ) `. So, how to access the object, without knowing it's name? – Josh Poor Oct 07 '17 at 08:23
  • 1
    Just use foreach loop with if statment according to your condition. – Osama Oct 07 '17 at 08:28
  • 1
    Btw, you misspelled json_decode – Josh Poor Oct 07 '17 at 09:21
1

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

Arka Roy
  • 170
  • 3
  • 15