博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
无法将stdClass类型的对象用作数组?
阅读量:2289 次
发布时间:2019-05-09

本文共 4894 字,大约阅读时间需要 16 分钟。

本文翻译自:

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 inC:\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楼

参考:


#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: 访问信息,我在控制器脚本上使用以下代码:

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,请记住它不是我要引用的数组,因此我使用对象操作符“->”访问记录,如下所示:

0){ foreach ($servicecalls as $servicecall) { echo '
' .$servicecall->ServiceCallDescription .''; }}else echo 'No service Calls';}?>
Raise New Service Call

#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;


#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']

转载地址:http://rscnb.baihongyu.com/

你可能感兴趣的文章
使用com.aspose.words将word模板转为PDF文件时乱码解决方法
查看>>
Linux发送邮件
查看>>
YUM安装PHP5.6
查看>>
YUM源安装MySQL5.7
查看>>
Tomcat日志切割cronolog
查看>>
glibc-2.14安装
查看>>
升级openssl zlib版本 安装nginx
查看>>
ab压力测试
查看>>
SVN指定端口启动
查看>>
网站访问速度一般检查参数
查看>>
编译安装过程
查看>>
HTTP常见返回码信息
查看>>
WEB集群session处理方案
查看>>
JDK命令行(jps、jstat、jinfo、jmap、jhat、jstack、jstatd、hprof)与JConsole
查看>>
JAVA 对象访问: 句柄和指针
查看>>
秒杀系统优化思路
查看>>
dubbo 报错:java.lang.NoClassDefFoundError: org/I0Itec/zkclient/exception/ZkNoNodeException
查看>>
logback的使用和logback.xml详解
查看>>
Linux 快捷键
查看>>
JPA 联合主键配置
查看>>