0
votes

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

4
You are getting a generic object back. us2.php.net/manual/en/function.json-decode.php - Schleis

4 Answers

3
votes

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'];
3
votes

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'};
0
votes

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

0
votes
 $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'];