开发者

Converting a string of JS Array to PHP array [duplicate]

This question already has answers here: How to convert JSON string to array (16 answers) Closed 9 months ago.

I 开发者_开发百科have a string (in PHP) representing a JS array, and for testing purpose would like to convert it to a PHP array to feed them into a unit test. Here's an example string

{ name: 'unique_name',fof: -1,range: '1',aoe: ',0,0,fp: '99,desc: 'testing ability,image: 'dummy.jpg'}

I could use a explode on the "," then on the colon, but that is rather inelegant. Is there a better way?


$php_object = json_decode($javascript_array_string)

This will return an object, with properties corresponding to the javascript array's properties. If you want an associative array, pass true as a second parameter to json_decode

$php_array = json_decode($javascript_array_string, true)

There is also a json_encode function for going the other way.


You are looking for json_decode().


json_decode

<?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)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜