【发布时间】:2012-11-28 07:33:48
【问题描述】:
我正在尝试解析 JSON 格式的字符串,但不知道该怎么做。这是我试图解析为 PHP 数组的字符串示例。
$json = '{"id":1,"name":"foo","email":"foo@test.com"}';
是否有一些库可以将 id、name 和 email 放入数组中?
【问题讨论】:
我正在尝试解析 JSON 格式的字符串,但不知道该怎么做。这是我试图解析为 PHP 数组的字符串示例。
$json = '{"id":1,"name":"foo","email":"foo@test.com"}';
是否有一些库可以将 id、name 和 email 放入数组中?
【问题讨论】:
您可以使用json_decode()
$json = '{"id":1,"name":"foo","email":"foo@test.com"}';
$object = json_decode($json);
Output:
{#775 ▼
+"id": 1
+"name": "foo"
+"email": "foo@test.com"
}
如何使用: $object->id //1
$array = json_decode($json, true /*[bool $assoc = false]*/);
Output:
array:3 [▼
"id" => 1
"name" => "foo"
"email" => "foo@test.com"
]
如何使用: $array['id'] //1
【讨论】:
可以使用json_decode() 完成,请务必将第二个参数设置为true,因为您需要的是数组而不是对象。
$array = json_decode($json, true); // decode json
输出:
Array
(
[id] => 1
[name] => foo
[email] => foo@test.com
)
【讨论】:
试试json_decode:
$array = json_decode('{"id":1,"name":"foo","email":"foo@test.com"}', true);
//$array['id'] == 1
//$array['name'] == "foo"
//$array['email'] == "foo@test.com"
【讨论】:
$obj=json_decode($json);
echo $obj->id; //prints 1
echo $obj->name; //prints foo
要将其放入数组中,只需执行以下操作即可
$arr = array($obj->id, $obj->name, $obj->email);
现在你可以像这样使用它了
$arr[0] // prints 1
【讨论】:
json_decode的第二个参数呢?现在你丢失了数组键,这在这里似乎很有用。