使用 PHP 访问 json 对象值
Access json object values with PHP
我有一个 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());
如果我打印出数据,我有这样的对象:
array(12) {
[0]=>
object(stdClass)#16 (3) {
["userId"]=>
string(3) "123"
["anotherId"]=>
string(3) "456"
["boolValue"]=>
bool(false)
}
}
如何访问这里的数据?我已经尝试过
$data = json_decode($response, true));
但 $response
不是字符串变量。
谢谢!
您已经解析了第 3 行中的 Json。
你应该可以去$data[0]->userId
什么的
编辑:请注意,$data
是一个对象数组,因此您必须遍历它们或指定要访问其中的一个。 [] 选择一个数组元素,然后 -> 访问对象上的一个字段
有时候get_object_vars
就够了。
我有一个 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());
如果我打印出数据,我有这样的对象:
array(12) {
[0]=>
object(stdClass)#16 (3) {
["userId"]=>
string(3) "123"
["anotherId"]=>
string(3) "456"
["boolValue"]=>
bool(false)
}
}
如何访问这里的数据?我已经尝试过
$data = json_decode($response, true));
但 $response
不是字符串变量。
谢谢!
您已经解析了第 3 行中的 Json。
你应该可以去$data[0]->userId
什么的
编辑:请注意,$data
是一个对象数组,因此您必须遍历它们或指定要访问其中的一个。 [] 选择一个数组元素,然后 -> 访问对象上的一个字段
有时候get_object_vars
就够了。