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

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.