将JSON字符串内容解析为PHP数组

时间:2012-11-28 07:33:49

标签: php json

我试图用JSON解析一个字符串,但不知道如何解决这个问题。这是我尝试解析为PHP数组的字符串示例。

$json = '{"id":1,"name":"foo","email":"foo@test.com"}';  

是否有一些库可以获取id,名称和电子邮件并将其放入数组中?

4 个答案:

答案 0 :(得分:12)

可以使用json_decode()完成,请确保将第二个参数设置为true,因为您需要一个数组而不是一个对象。

$array = json_decode($json, true); // decode json

输出:

Array
(
    [id] => 1
    [name] => foo
    [email] => foo@test.com
)

答案 1 :(得分:4)

尝试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"

答案 2 :(得分:4)

$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

答案 3 :(得分:0)

$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

相关问题