search
Homephp教程php手册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 
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 ) 
      
)

后来百度搜索一个关于差不多的问题,但对方是json数据,php再调用json_decode从字符串对象生成json对象时,如果使用[]操作符取数据,会得到下面的错误:

Cannot use object of type stdClass as array

产生原因,代码如下:

$res = json_decode($res);

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

解决方法,2种:

1、使用 json_decode($d, true),就是使json_decode 的第二个变量设置为 true.

2、json_decode($res) 返回的是一个对象,不可以使用 $res['key'] 进行访问,换成 $res->key 就可以了.

好了现在回到我们原问题发现原来是不能直接用[]来显示导致的,上面代码的输出是用的:$pic[0][title],改为$pic[0]->title后正常了.


文章链接:

随便收藏,请保留本文地址!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.