I have a string containing a Javascript array the next way:
$array = "var Array = [
{ 'a' : 'val1', 'b': 1},
{ 'a' : 'val2', 'b': 2}
];";
How can I convert this string to a PHP array in the next structure:
$array[0] => array('a' => 'val1', 'b' => 1)
$array[1] => array('a' => 'val2', 'b' => 2)
Thanks
You should definitely look into using json to communicate code between php and js. However, I don't know what you want to use this code for, so this is does what you want (as a general rule, you don't want to use that):
<?php
$str = 'var Array = [
{"a": "val1", "b": 1},
{"a": "val2", "b": 2}
];';
$matches = array();
preg_match("/^(var\s+)*([A-Za-z0-9_\.]+)\s*=\s*([^;]+);$/", $str, $matches);
print "<pre>";
var_dump($matches);
print "</pre>";
$array = json_decode($matches[3], true);
print "<pre>";
var_dump($array);
print "</pre>";
?>
Also note that I had to replace the single quotes with double quotes for this to work, I have no idea why I had to do that.
If you say why you need this, you might get a little more help.
This will Help:
Example :
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above example will output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
from here.
You should use JSON for this.
Please look carefully at the differences I made, JSON syntax is much stricter than javascript object initializer syntax.
$array = '[
{ "a" : "val1", "b": 1},
{ "a" : "val2", "b": 2}
]';
$array = json_decode($array, true );
print_r($array);
/*
Array
(
[0] => Array
(
[a] => val1
[b] => 1
)
[1] => Array
(
[a] => val2
[b] => 2
)
)
*/