1

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How so? There is no single array list. And changing the problem domain from a JS expression to a fictional and flat JSON string makes this a non-answer.
2

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.

2 Comments

php.net/manual/en/v8js.executestring.php would probably better than regex :P
@Esailija Post it as an answer.... or is it ironic? :) But it seems as a good solution... why the :P. You are confusing!
0

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
        )

)

*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.