Access json object values with PHP

2k Views Asked by At

I have a php script that pulls in json data like below:

$request = new HTTP_Request2('https://fakeurl.com/stuff', HTTP_Request2::METHOD_GET);
$request->setHeader('Authorization', 'Bearer ' . $access_token);  
$response = $request->send();  
$data = json_decode($response->getBody()); 

If I print out the data I have objects like this:

  array(12) {
    [0]=>
    object(stdClass)#16 (3) {
      ["userId"]=>
      string(3) "123"
      ["anotherId"]=>
      string(3) "456"
      ["boolValue"]=>
      bool(false)
    }
  }

How can I access the data in here? I already tried doing

$data = json_decode($response, true));

but $response isn't a string variable.

Thanks!

2

There are 2 best solutions below

1
On BEST ANSWER

You already parse the Json in line 3.

You should be able to go $data[0]->userId or something

Edit: Notice that $data is an array of objects so you have to loop through them or specify which one of them you want to access. [] to choose an array element and then -> to access a field on the object

0
On

Sometimes get_object_vars is enough.

[http://php.net/manual/en/function.get-object-vars.php][1]