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

其他回答

函数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'],你把它作为一个数组,错误它告诉你,你实际上是在处理一个对象,那么你应该访问它作为$result->context

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

$result = json_decode($data, true);

为了从json字符串中得到一个数组,你应该将第二个参数设置为boolean true。

$result = json_decode($json_string, true);
$context = $result['context'];

否则$result将是一个std对象。但是您可以以对象的形式访问值。

  $result = json_decode($json_string);
 $context = $result->context;

使用true作为json_decode的第二个参数。这将把json解码成一个关联数组,而不是stdObject实例:

$my_array = json_decode($my_json, true);

有关详细信息,请参阅文档。