使用PHP访问json对象值

时间:2023-01-05 21:37:56

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

我有一个php脚本,可以输入如下的json数据:

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

但$ response不是字符串变量。

Thanks!

谢谢!

2 个解决方案

#1


2  

You already parse the Json in line 3.

你已经在第3行解析了Json。

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

你应该可以去$ data [0] - > userId或者什么

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

编辑:请注意,$ data是一个对象数组,因此您必须遍历它们或指定要访问哪一个。 []选择数组元素,然后 - >访问对象上的字段

#2


0  

Sometimes get_object_vars is enough.

有时get_object_vars就足够了。

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

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

#1


2  

You already parse the Json in line 3.

你已经在第3行解析了Json。

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

你应该可以去$ data [0] - > userId或者什么

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

编辑:请注意,$ data是一个对象数组,因此您必须遍历它们或指定要访问哪一个。 []选择数组元素,然后 - >访问对象上的字段

#2


0  

Sometimes get_object_vars is enough.

有时get_object_vars就足够了。

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

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