我有一個字符串(在PHP中)表示一個JS數組,並且爲了測試目的而想將其轉換爲PHP數組以將它們饋送到單元測試中。這裏有一個例子字符串將JS數組的字符串轉換爲PHP數組
{ name: 'unique_name',fof: -1,range: '1',aoe: ',0,0,fp: '99,desc: 'testing ability,image: 'dummy.jpg'}
我可以使用的「」然後發生爆炸結腸,但是這是相當不雅。有沒有更好的辦法?
我有一個字符串(在PHP中)表示一個JS數組,並且爲了測試目的而想將其轉換爲PHP數組以將它們饋送到單元測試中。這裏有一個例子字符串將JS數組的字符串轉換爲PHP數組
{ name: 'unique_name',fof: -1,range: '1',aoe: ',0,0,fp: '99,desc: 'testing ability,image: 'dummy.jpg'}
我可以使用的「」然後發生爆炸結腸,但是這是相當不雅。有沒有更好的辦法?
$php_object = json_decode($javascript_array_string)
這將返回一個對象,其屬性對應於javascript數組的屬性。如果你想要一個關聯數組,傳遞true作爲第二個參數json_decode
$php_array = json_decode($javascript_array_string, true)
還爲走另一條路一json_encode函數
您正在尋找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)
}