PHP Fatal Error:cannot Use object of type StdClass as array in error

Source: Internet
Author: User
Tags json

Let's look at the solution to the problem of PHP Fatal error:cannot use object of type StdClass as array error in PHP development.

The following error occurred with the normal array

The code is as follows

<?php
Array (
[0] => StdClass Object (
[ID] => 1
[Title] => Wonderful recommendation
[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)
)
?>

Then Baidu searched for a question about the same, but the other side was JSON data

When PHP calls Json_decode to generate a JSON object from a string object, if you use the [] operator to fetch the data, you get the following error:

Cannot use object of type StdClass as array

Causes:

The code is as follows

$res = Json_decode ($res);
$res [' key ']; Use the object after Json_decode () as an array.

Solution (2 kinds):

1. Use Json_decode ($d, True). is to make the second variable of Json_decode set to true.

2, Json_decode ($res) Returns an object, can not use the $res [' key '] for access, replaced $res->key on it.

All right, now back to our original problem.

The original is not directly with [] to show the resulting, the above code output is used: $pic [0][title], changed to $pic[0]->title after 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.