如何从PHP中的json响应中提取键值

时间:2021-02-11 16:04:48

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

2 个解决方案

#1


8  


    // 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;

#2


1  

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:

它已经解码了,正如你在man手册页上看到的那样,json_decode的默认行为是将JSON字符串解码为stdClass的实例,如果你想要一个assoc数组,只需写:

$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:

但是你可以只访问对象的更新值,因为它只是一个公共属性:

$obj = json_decode($string);
echo $obj->updated;

#1


8  


    // 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;

#2


1  

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:

它已经解码了,正如你在man手册页上看到的那样,json_decode的默认行为是将JSON字符串解码为stdClass的实例,如果你想要一个assoc数组,只需写:

$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:

但是你可以只访问对象的更新值,因为它只是一个公共属性:

$obj = json_decode($string);
echo $obj->updated;