我使用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()返回的数据
如何读取这个数组中的值?
当前回答
有时候在使用API时,你只是想保持一个对象为对象。要访问有嵌套对象的对象,您可以执行以下操作:
我们假设当你print_r对象时,你可能会看到:
print_r($response);
stdClass object
(
[status] => success
[message] => Some message from the data
[0] => stdClass object
(
[first] => Robert
[last] => Saylor
[title] => Symfony Developer
)
[1] => stdClass object
(
[country] => USA
)
)
访问对象的第一部分:
print $response->{'status'};
这将输出"success"
现在让我们调整其他部分:
$first = $response->{0}->{'first'};
print "First name: {$first}<br>";
预期的输出是“Robert”和换行符。
您还可以将对象的一部分重新分配给另一个对象。
$contact = $response->{0};
print "First Name: " . $contact->{'first'} . "<br>";
预期的输出是“Robert”和换行符。
访问下一个键“1”的过程是相同的。
print "Country: " . $response->{1}->{'country'} . "<br>";
预期输出将是“美国”
希望这能帮助你理解对象以及我们为什么要将对象保持为对象。您不应该需要将对象转换为数组来访问其属性。
其他回答
您必须使用->访问它,因为它是一个对象。
更改您的代码:
$result['context'];
To:
$result->context;
你可以像这样将stdClass对象转换为数组:
$array = (array)$stdClass;
stdclass到数组
改成
$results->fetch_array()
当你试图访问它作为$result['context'],你把它作为一个数组,错误它告诉你,你实际上是在处理一个对象,那么你应该访问它作为$result->context
使用json_decode的第二个参数使它返回一个数组:
$result = json_decode($data, true);