我使用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>";

预期输出将是“美国”

希望这能帮助你理解对象以及我们为什么要将对象保持为对象。您不应该需要将对象转换为数组来访问其属性。

其他回答

你可以像这样将stdClass对象转换为数组:

$array = (array)$stdClass;

stdclass到数组

今天遇到同样的问题,是这样解决的:

如果你调用json_decode($somestring),你会得到一个对象,你需要访问像$ Object ->key,但如果你调用json_decode($somestring, true),你会得到一个字典,可以访问像$array['key']

下面是函数签名:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

当param为false(默认值)时,它将返回适当的php类型。您可以使用object获取该类型的值。方法范式。

当param为true时,它将返回关联数组。

它将在错误时返回NULL。

如果你想通过数组获取值,将assoc设置为true。

正如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

使用json_decode的第二个参数使它返回一个数组:

$result = json_decode($data, true);