【问题标题】:JSON Decode Fatal error: Cannot use object of type stdClass as array inJSON解码致命错误:不能使用stdClass类型的对象作为数组
【发布时间】:2014-07-18 06:35:43
【问题描述】:

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

$states='{
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa",
    "AZ": "Arizona",
    "AR": "Arkansas"

}';

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

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

【问题讨论】:

标签: php json


【解决方案1】:

你看,json_decode() 方法不会将我们的 JSON 作为 PHP 数组返回;它使用一个 stdClass 对象来表示我们的数据。让我们将对象键作为对象属性访问。

echo $stateList->AL;

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

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

【讨论】:

    【解决方案2】:

    要么你把true传给json_decode,就像南河说的:

    $stateList = json_decode($states, true);
    

    或更改您访问它的方式:

    echo $stateList->{'AL'};
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:
         $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'];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-05
          • 1970-01-01
          • 1970-01-01
          • 2023-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多