Home >Backend Development >PHP Tutorial >PHP Fatal error: Cannot use object of type stdClass as array in错误_PHP教程

PHP Fatal error: Cannot use object of type stdClass as array in错误_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:20:45992browse

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

Let’s take a look at PHP Fatal error: Cannot use object of type stdClass encountered in PHP development The solution to the as array in error problem.

The following error occurs with ordinary arrays

The code is as follows

Array (
[0] => stdClass Object (
[id] => 1
[title] =>Wonderful recommendations
[size] => 280*150
[pic] => ./uploadfiles/201402160422.jpg
[state] => 0 )
[1] => stdClass Object (
[id] => 2
[title] =>Corporate News
[size] => 280*150
[pic] => ./uploadfiles/201402160533.jpg
[state] => 0 )
)
?>

 代码如下  

Array (
[0] => stdClass Object (
  [id] => 1
  [title] =>精彩推荐
  [size] => 280*150
  [pic] => ./uploadfiles/201402160422.jpg
  [state] => 0 )
 [1] => stdClass Object (
  [id] => 2
  [title] =>企业要闻
  [size] => 280*150
  [pic] => ./uploadfiles/201402160533.jpg
  [state] => 0 )
 )
?>

Later, Baidu searched for a similar question, but the other party was json data

When PHP calls json_decode to generate a json object from a string object, if you use the [] operator to get data, you will get the following error:

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.

 代码如下  

$res = json_decode($res);
$res['key']; //把 json_decode() 后的对象当作数组使用。

Solutions (2 types):

1. Use json_decode($d, true). Just set the second variable of json_decode to true.

 2. json_decode($res) returns an object and cannot be accessed using $res['key']. Just replace it with $res->key.

Okay, now back to our original problem discovery

It turns out that the problem is that [] cannot be used directly to display. The output of the above code is: $pic[0][title]. After changing it to $pic[0]->title, it becomes normal

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/865527.htmlTechArticlePHP Fatal error: Cannot use object of type stdClass as array in error Let’s take a look at the errors encountered in PHP development To PHP Fatal error: Cannot use object of type stdClass as array in error question...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn