如何从 PHP 中的 json 响应中按键提取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26932852/
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
How to extract value by key from json response in PHP
提问by user1610208
I'm using getResponse api for getting updated about subscribers.
This is what is printing after var_dump($result);
我正在使用 getResponse api 来获取有关订阅者的更新信息。这是打印后的内容var_dump($result);
object(stdClass)#2 (1) {
["updated"]=>
int(1)
}
How do i extract / decode / encode the result to request the key: "update" and get it's value: 1 ?
我如何提取/解码/编码结果以请求密钥:“更新”并获取其值:1?
Thanks
谢谢
回答by reshetech
// json object. $contents = '{"firstName":"John", "lastName":"Doe"}'; // Option 1: through the use of an array. $jsonArray = json_decode($contents,true); $key = "firstName"; $firstName = $jsonArray[$key]; // Option 2: through the use of an object. $jsonObj = json_decode($contents); $firstName = $jsonObj->$key;
回答by Elias Van Ootegem
It's already decoded, as you can see on the man pages, the default behavior of json_decode
is to decode a JSON string to an instance of stdClass
, if you want an assoc array, simply write:
它已经被解码,正如您在手册页上看到的那样,默认行为json_decode
是将 JSON 字符串解码为 的实例stdClass
,如果您想要一个关联数组,只需编写:
$string = '{"updated":1}';
$array = json_decode($string, true);
echo $array['updated'];
But you can just access the updated
value on the object, because it's just a public property anyway:
但是您只能访问updated
对象上的值,因为无论如何它只是一个公共属性:
$obj = json_decode($string);
echo $obj->updated;