本文翻译自:Cannot use object of type stdClass as array?

I get a strange error using json_decode() . 我使用json_decode()得到一个奇怪的错误。 It decode correctly the data (I saw it using print_r ), but when I try to access to info inside the array I get: 它可以正确解码数据(我使用print_r看到了),但是当我尝试访问数组中的信息时,我得到了:

Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108

I only tried to do: $result['context'] where $result has the data returned by json_decode() 我只是尝试做: $result['context']其中$result具有json_decode()返回的数据

How can I read values inside this array? 如何读取此数组中的值?


#1楼

参考:https://stackoom.com/question/Sb1k/无法将stdClass类型的对象用作数组


#2楼

instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB: 而不是使用括号,而是使用对象运算符,例如,基于数据库对象的数组是在名为DB的类中这样创建的:

class DB {
private static $_instance = null;
private $_pdo,$_query, $_error = false,$_results,$_count = 0;private function __construct() {try{$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );} catch(PDOException $e) {$this->_error = true;$newsMessage = 'Sorry.  Database is off line';$pagetitle = 'Teknikal Tim - Database Error';$pagedescription = 'Teknikal Tim Database Error page';include_once 'dbdown.html.php';exit;}$headerinc = 'header.html.php';
}public static function getInstance() {if(!isset(self::$_instance)) {self::$_instance = new DB();}return self::$_instance;}public function query($sql, $params = array()) {$this->_error = false;if($this->_query = $this->_pdo->prepare($sql)) {$x = 1;if(count($params)) {foreach($params as $param){$this->_query->bindValue($x, $param);$x++;}}}if($this->_query->execute()) {$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);$this->_count = $this->_query->rowCount();}else{$this->_error = true;}return $this;
}public function action($action, $table, $where = array()) {if(count($where) ===3) {$operators = array('=', '>', '<', '>=', '<=');$field      = $where[0];$operator   = $where[1];$value      = $where[2];if(in_array($operator, $operators)) {$sql = "{$action} FROM {$table} WHERE {$field} = ?";if(!$this->query($sql, array($value))->error()) {return $this;}}}return false;
}public function get($table, $where) {return $this->action('SELECT *', $table, $where);public function results() {return $this->_results;
}public function first() {return $this->_results[0];
}public function count() {return $this->_count;
}}

to access the information I use this code on the controller script: 访问信息,我在控制器脚本上使用以下代码:

<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID','=','$_SESSION['UserID']));if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';?>

then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it's not an array I am referencing so I access the records with the object operator "->" like this: 然后显示信息,以检查是否设置了服务调用并且计数大于0,请记住它不是我要引用的数组,因此我使用对象操作符“->”访问记录,如下所示:

<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from theheader -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article><h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){foreach ($servicecalls as $servicecall) {echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'.$servicecall->ServiceCallDescription .'</a>';}
}else echo 'No service Calls';}?>
<a href="/servicecalls/?new=true">Raise New Service Call</a>
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>

#3楼

You must access it using -> since its an object. 您必须使用->来访问它,因为它是一个对象。

Change your code from: 从以下位置更改代码:

$result['context'];

To: 至:

$result->context;

#4楼

You can convert stdClass object to array like: 您可以将stdClass对象转换为数组,例如:

$array = (array)$stdClass;

stdClsss to array stdClsss数组


#5楼

Here is the function signature: 这是函数签名:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

When param is false, which is default, it will return an appropriate php type. 当param为false时(默认设置),它将返回适当的php类型。 You fetch the value of that type using object.method paradigm. 您可以使用object.method范例获取该类型的值。

When param is true, it will return associative arrays. 当param为true时,它将返回关联数组。

It will return NULL on error. 错误时将返回NULL。

If you want to fetch value through array, set assoc to true. 如果要通过数组获取值,请将assoc设置为true。


#6楼

Have same problem today, solved like this: 今天有同样的问题,像这样解决:

If you call json_decode($somestring) you will get an Object and you need to access like $object->key , but if u call json_decode($somestring, true) you will get an dictionary and can access like $array['key'] 如果调用json_decode($somestring)您将获得一个对象,并且需要像$object->key那样进行访问;但是,如果您调用json_decode($somestring, true) ,则将得到一个字典,并且可以像$array['key']

无法将stdClass类型的对象用作数组?相关推荐

  1. php不能使用class,php – 致命错误:不能使用stdClass类型的对象作为数组

    我知道这可能很简单,我开始明白我需要怎么做,我意识到这与OO有关但是因为我是OO和json的新手我对这个 http://api.discogs.com/database/search?q=d& ...

  2. java 数组对象属性数组_Java中数组的特性

    数组是基本上所有语言都会有的一种数据类型,它表示一组相同类型的数据的集合,具有固定的长度,并且在内存中占据连续的空间.在C,C++等语言中,数组的定义简洁清晰,而在java中确有一些会让人迷惑的特性. ...

  3. php的对象和数组应该学js,JavaScript数组与对象的常用方法及 json 的序列化

    一.JavaScript数据类型: 1- 原始类型:number(数值),string(字符串),boolean(布尔值)var age = 18; var username = "admi ...

  4. .net Mvc Controller 接收 Json/post方式 数组 字典 类型 复杂对象

    原文地址:http://www.cnblogs.com/fannyatg/archive/2012/04/16/2451611.html ------------------------------- ...

  5. 实验5.6 定义包含5个元素的对象数组,每个元素都是Employee类型的对象

    题目 定义包含5个元素的对象数组,每个元素都是Employee类型的对象. Employee类,其中包括姓名.街道地址.城市和邮编等属性,以及change_name()和display()等函数.di ...

  6. Ts定义对象和数组类型

    // 一. 对象类型-接口// 1. // 定义了一个接口 Person(行为的抽象,事物的本质), interface Person1 {name:string;age:number; }// 接着 ...

  7. php一个数组赋值给对象,php数组与对象相互转换方法

    php教程数组与对象相互转换方法 function arrayToObject($e){ if( gettype($e)!='array' ) return; foreach($e as $k=> ...

  8. JS如何深度复制对象和数组,避免指针变量引用修改值

    //自定义深度复制对象or数组的递归方法---------------------------------------- let copyObjOrArr = o => {let isArray ...

  9. json vue 对象转数组_vue 基础入门(一)修改

    vue基础入门(一) 1. 什么是vue Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的渐进式框架. Vue 只关注视图层, 采用自底向上增量开发的设计. Vue 的目标 ...

最新文章

  1. 伏安特性实验误差分析_人教高中物理必修第三册《3 实验:电池电动势和内阻的测量》...
  2. maile:教你程序员怎么发邮件
  3. 【Linux】时间戳与正常日期
  4. 面试分享:那些年我经历过的一些面试,以及得到的一些面试心得!
  5. powershell一行代码批量修改文件名(附命令详解)
  6. js 把字符串格式化成时间
  7. 笔记本装服务器系统 无线网卡无法驱动,笔记本Win8.1系统无线网卡驱动装不上如何解决...
  8. Asterisk 对VoiceXML 及CSTA的支持
  9. html怎样使图片自动旋转,css怎么让图片旋转?
  10. 刘易斯拐点对中国经济的影响
  11. SAP 信息记录条件 无法维护多个条件
  12. 1688按关键词搜索示例
  13. [JZOJ5551] 【NOI2019模拟6.24】旅途【最短路】
  14. 【项目】出库流程记录
  15. 【WebGIS】leaflet入门-自定义MarkerIcon
  16. 如何对研发团队绩效进行考核?【附各环节人员考核参考表】
  17. 如何能更更好的装逼 (Windows CMD命令大全)
  18. 手机访问计算机FTP服务器
  19. ISO26262 功能安全(1)--概览学习
  20. python网易云_[Python] 网易云歌单/歌曲下载

热门文章

  1. Android之ViewHolder用法
  2. Android 开发包括哪些方面?如何提升?
  3. Swift JSON转模型Xcode插件
  4. (018)java后台开发之语法输出流flush()方法
  5. swift_003(Swift的?和!)
  6. (0001) iOS 开发之收集第三方资源篇
  7. ORA-20011 ORA-29913 KUP-11024 GATHER_TABLE_STATS
  8. git cmd 命令在已有的仓库重新添加新的文件夹
  9. HDU 4614 Vases and Flowers 【线段树】+【二分】
  10. 2017-2018-1 20155327 实验五 通讯协议设计