2010-01-26 129 views
1

我有一个字符串(在PHP中)表示一个JS数组,并且为了测试目的而想将其转换为PHP数组以将它们馈送到单元测试中。这里有一个例子字符串将JS数组的字符串转换为PHP数组

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

我可以使用的“”然后发生爆炸结肠,但是这是相当不雅。有没有更好的办法?

回答

4
$php_object = json_decode($javascript_array_string) 

这将返回一个对象,其属性对应于javascript数组的属性。如果你想要一个关联数组,传递true作为第二个参数json_decode

$php_array = json_decode($javascript_array_string, true) 

还为走另一条路一json_encode函数

0

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)); 

?> 

上例将输出:

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