PHP Fatal error: Cannot use object of type stdClass as array in error
Let's take a look at the solution to the php Fatal error: Cannot use object of type stdClass as array in during PHP development.
The following error occurs in a common array:
| The Code is as follows: |
|
|
<? Php
Array (
[0] => stdClass Object (
[Id] => 1
[Title] => excellent recommendations
[Size] => 280*150
[Pic] =>./uploadfiles/201402160422.jpg
[State] => 0)
[1] => stdClass Object (
[Id] => 2
[Title] => enterprise news
[Size] => 280*150
[Pic] =>./uploadfiles/201402160533.jpg
[State] => 0)
)
?> |
Later, Baidu searched for a similar question, but the other side was json data.
When php calls json_decode to generate a json object from a string object, if the [] operator is used to retrieve data, the following error is returned:
Cannot use object of type stdClass as array
Cause:
| The Code is as follows: |
|
|
$ Res = json_decode ($ res );
$ Res ['key']; // use the object after json_decode () as an array. |
Solution (2 types ):
1. Use json_decode ($ d, true ). The second variable of json_decode is set to true.
2. json_decode ($ res) returns an object. You cannot use $ res ['key'] for access. You can replace it with $ res-> key.
Now let's go back to our original issue and find out
It turns out that [] cannot be directly used for display. The output of the above Code is: $ pic [0] [title], changed to $ pic [0]-> title, which is normal.