我正在尝试解析一个JSON字符串,但不确定如何操作。这是我要解析为PHP数组的字符串示例。
$json = '{"id":1,"name":"foo","email":"foo@test.com"}';
有没有一些库可以将id、name和email取出并放入一个数组中?
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 = '{"id":1,"name":"foo","email":"foo@test.com"}';
$object = json_decode($json);
Output:
{#775 ▼
+"id": 1
+"name": "foo"
+"email": "foo@test.com"
}
$array = json_decode($json, true /*[bool $assoc = false]*/);
Output:
array:3 [▼
"id" => 1
"name" => "foo"
"email" => "foo@test.com"
]
json_decode
的第二个参数呢?现在你失去了数组键,这在这里似乎非常有用。 - mkilmanas