How to extract value by key from json response in

2020-06-16 03:08发布

问题:

I'm using getResponse api for getting updated about subscribers. This is what is printing after 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 ?

Thanks

回答1:


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

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:

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


标签: php json