JSON解码致命错误:无法将stdClass类型的对象用作中的数组


JSON Decode Fatal error: Cannot use object of type stdClass as array in

我有JSON格式的状态列表,我正在使用JSON_decode函数,但当我试图访问数组值时出错。

$states='{
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa",
    "AZ": "Arizona",
    "AR": "Arkansas"
}';
$stateList = json_decode($states);
echo $stateList['AL'];

致命错误:无法将stdClass类型的对象用作第65行的数组

您可以看到,json_decode((方法不会将json作为PHP数组返回;它使用stdClass对象来表示我们的数据。让我们将对象键作为对象属性进行访问。

echo $stateList->AL;

如果您提供true作为函数的第二个参数,我们将准确地收到我们的PHP数组正如预期的那样。

$stateList = json_decode($states,true);
echo $stateList['AL'];

要么像南河说的那样将true传递给json_decode

$stateList = json_decode($states, true);

或者更改访问方式:

echo $stateList->{'AL'};

您可以将true作为第二个参数传递给json_encode,或者显式地将类转换为数组。我希望这能有所帮助。

 $stateList = json_decode($states);
 //statelist is a object so you can not access it as array
 echo $stateList->AL;

如果你想在解码后得到一个数组:

  $stateList = json_decode($states, true);
 //statelist is an array so you can not access it as array
 echo $stateList['AL'];