简体   繁体   中英

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

I have state list in JSON format and i am using json_decode function but when i am trying to access array values getting error.

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

}';

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

Fatal error: Cannot use object of type stdClass as array on line 65

You see, the json_decode() method doesn't return our JSON as a PHP array; it uses a stdClass object to represent our data. Let's instead access our object key as an object attribute.

echo $stateList->AL;

If you provide true as the second parameter to the function we will receive our PHP array exactly as expected.

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

Either you pass true to json_decode like Nanhe said:

$stateList = json_decode($states, true);

or change the way you access it:

echo $stateList->{'AL'};

You could pass true as the second parameter to json_encode or explicitly convert the class to array. I hope that helps.

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

If you want to get an array as a result after decode :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM