无法将stdClass类型的对象用作数组?

本文翻译自: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 the
  header -->
<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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值