我使用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()返回的数据
如何读取这个数组中的值?
当前回答
改成
$results->fetch_array()
其他回答
正如Php手册所说,
print_r -打印关于变量的人类可读信息
当我们使用json_decode();时,我们得到一个stdClass类型的对象作为返回类型。 要在print_r()内部传递的参数应该是数组或字符串。因此,不能在print_r()中传递对象。我找到了两种处理方法。
将对象强制转换为数组。 这可以通过以下方式实现。 $a =(数组)$object 通过访问对象的键 如前所述,当您使用json_decode();函数,它返回一个stdClass对象。您可以在-> Operator的帮助下访问对象的元素。 $value = $object->key;
第一,如果对象有嵌套数组,也可以使用多个键来提取子元素。
$value = $object->key1->key2->key3...;
它们还有print_r()的其他选项,如var_dump();和var_export ();
另外,如果你设置了json_decode()的第二个参数;为true时,它将自动将对象转换为数组(); 以下是一些参考资料: http://php.net/manual/en/function.print-r.php http://php.net/manual/en/function.var-dump.php http://php.net/manual/en/function.var-export.php
你可以像这样将stdClass对象转换为数组:
$array = (array)$stdClass;
stdclass到数组
当你试图访问它作为$result['context'],你把它作为一个数组,错误它告诉你,你实际上是在处理一个对象,那么你应该访问它作为$result->context
使用json_decode的第二个参数使它返回一个数组:
$result = json_decode($data, true);
试试像这样的东西!
而不是像这样获取上下文(这适用于获取数组下标)
$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;
}