我使用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()默认返回一个对象。

你可以像这样访问数据:

var_dump($result->context);

如果你有像from-date这样的标识符(在使用上面的方法时,连字符会导致PHP错误),你必须写:

var_dump($result->{'from-date'});

如果你想要一个数组,你可以这样做:

$result = json_decode($json, true);

或者将对象转换为数组:

$result = (array) json_decode($json);

其他回答

您必须使用->访问它,因为它是一个对象。

更改您的代码:

$result['context'];

To:

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

函数json_decode()默认返回一个对象。

你可以像这样访问数据:

var_dump($result->context);

如果你有像from-date这样的标识符(在使用上面的方法时,连字符会导致PHP错误),你必须写:

var_dump($result->{'from-date'});

如果你想要一个数组,你可以这样做:

$result = json_decode($json, true);

或者将对象转换为数组:

$result = (array) json_decode($json);

改成

$results->fetch_array()