我使用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()返回的数据
如何读取这个数组中的值?
当前回答
你可以像这样将stdClass对象转换为数组:
$array = (array)$stdClass;
stdclass到数组
其他回答
为了从json字符串中得到一个数组,你应该将第二个参数设置为boolean true。
$result = json_decode($json_string, true);
$context = $result['context'];
否则$result将是一个std对象。但是您可以以对象的形式访问值。
$result = json_decode($json_string);
$context = $result->context;
有时候在使用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']
尝试(获取对象的工作)
$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;
}
下面是函数签名:
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()默认返回一个对象。
你可以像这样访问数据:
var_dump($result->context);
如果你有像from-date这样的标识符(在使用上面的方法时,连字符会导致PHP错误),你必须写:
var_dump($result->{'from-date'});
如果你想要一个数组,你可以这样做:
$result = json_decode($json, true);
或者将对象转换为数组:
$result = (array) json_decode($json);