我使用json_decode()得到一个奇怪的错误。它正确解码数据(我看到它使用print_r),但当我试图访问数组内的信息时,我得到:
Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108
我只想做:$result['context']其中$result有json_decode()返回的数据
如何读取这个数组中的值?
我使用json_decode()得到一个奇怪的错误。它正确解码数据(我看到它使用print_r),但当我试图访问数组内的信息时,我得到:
Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108
我只想做:$result['context']其中$result有json_decode()返回的数据
如何读取这个数组中的值?
当前回答
使用json_decode的第二个参数使它返回一个数组:
$result = json_decode($data, true);
其他回答
下面是函数签名:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
当param为false(默认值)时,它将返回适当的php类型。您可以使用object获取该类型的值。方法范式。
当param为true时,它将返回关联数组。
它将在错误时返回NULL。
如果你想通过数组获取值,将assoc设置为true。
今天遇到同样的问题,是这样解决的:
如果你调用json_decode($somestring),你会得到一个对象,你需要访问像$ Object ->key,但如果你调用json_decode($somestring, true),你会得到一个字典,可以访问像$array['key']
我突然得到了这个错误,因为我的facebook登录突然停止工作(我也换了主机),并抛出了这个错误。修复真的很简单
问题出在这段代码中
$response = (new FacebookRequest(
FacebookSession::newAppSession($this->appId, $this->appSecret),
'GET',
'/oauth/access_token',
$params
))->execute()->getResponse(true);
if (isset($response['access_token'])) { <---- this line gave error
return new FacebookSession($response['access_token']);
}
基本上,isset()函数期望一个数组,但它却找到一个对象。简单的解决方案是使用(array)量词将PHP对象转换为数组。下面是固定代码。
$response = (array) (new FacebookRequest(
FacebookSession::newAppSession($this->appId, $this->appSecret),
'GET',
'/oauth/access_token',
$params
))->execute()->getResponse(true);
注意在第一行中使用了off array()量词。
试试像这样的东西!
而不是像这样获取上下文(这适用于获取数组下标)
$result['context']
尝试(获取对象的工作)
$result->context
其他例子是:(如果$result有多个数据值)
Array
(
[0] => stdClass Object
(
[id] => 15
[name] => 1 Pc Meal
[context] => 5
[restaurant_id] => 2
[items] =>
[details] => 1 Thigh (or 2 Drums) along with Taters
[nutrition_fact] => {"":""}
[servings] => menu
[availability] => 1
[has_discount] => {"menu":0}
[price] => {"menu":"8.03"}
[discounted_price] => {"menu":""}
[thumbnail] => YPenWSkFZm2BrJT4637o.jpg
[slug] => 1-pc-meal
[created_at] => 1612290600
[updated_at] => 1612463400
)
)
然后试试这个:
foreach($result as $results)
{
$results->context;
}
使用json_decode的第二个参数使它返回一个数组:
$result = json_decode($data, true);