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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13600024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:45:33  来源:igfitidea点击:

Parse JSON string contents into PHP Array

phpjson

提问by tony2

I am trying to parse a string in JSON, but not sure how to go about this. This is an example of the string I am trying to parse into a PHP array.

我正在尝试解析 JSON 中的字符串,但不知道如何处理。这是我试图解析为 PHP 数组的字符串示例。

$json = '{"id":1,"name":"foo","email":"[email protected]"}';  

Is there some library that can take the id, name, and email and put it into an array?

是否有一些库可以将 id、name 和 email 放入数组中?

回答by MrCode

It can be done with json_decode(), be sure to set the second argument to truebecause you want an array rather than an object.

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

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

Outputs:

输出:

Array
(
    [id] => 1
    [name] => foo
    [email] => [email protected]
)

回答by Musa

Try json_decode:

尝试json_decode

$array = json_decode('{"id":1,"name":"foo","email":"[email protected]"}', true);
//$array['id'] == 1
//$array['name'] == "foo"
//$array['email'] == "[email protected]"

回答by Errol Fitzgerald

$obj=json_decode($json);  
echo $obj->id; //prints 1  
echo $obj->name; //prints foo

To put this an array just do something like this

把它放在一个数组中,只需做这样的事情

$arr = array($obj->id, $obj->name, $obj->email);

Now you can use this like

现在你可以像这样使用它

$arr[0] // prints 1

回答by Ilya Degtyarenko

You can use json_decode()

您可以使用json_decode()

$json = '{"id":1,"name":"foo","email":"[email protected]"}';  

$object = json_decode($json);

Output: 
    {#775 ▼
      +"id": 1
      +"name": "foo"
      +"email": "[email protected]"
    }

How to use:$object->id//1

使用方法:$object->id//1

$array = json_decode($json, true /*[bool $assoc = false]*/);

Output:
    array:3 [▼
      "id" => 1
      "name" => "foo"
      "email" => "[email protected]"
    ]

How to use:$array['id']//1

使用方法:$array['id']//1