首页 文章

不能使用stdClass类型的对象作为数组?

提问于
浏览
417

我使用 json_decode() 得到一个奇怪的错误 . 它正确解码数据(我使用 print_r 看到它),但是当我尝试访问数组中的信息时,我得到:

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

我只是试图这样做: $result['context'] 其中 $resultjson_decode() 返回的数据

如何读取此数组中的值?

13 回答

  • 48

    使用json_decode的第二个参数使其返回一个数组:

    $result = json_decode($data, true);
    
  • 7

    函数json_decode()默认返回一个对象 .

    您可以像这样访问数据:

    var_dump($result->context);
    

    如果您有 from-date 之类的标识符(使用上述方法时连字符会导致PHP错误)您必须编写:

    var_dump($result->{'from-date'});
    

    如果你想要一个数组,你可以这样做:

    $result = json_decode($json, true);
    

    或者将对象强制转换为数组:

    $result = (array) json_decode($json);
    
  • 68

    您必须使用 -> 来访问它,因为它是一个对象 .

    更改您的代码:

    $result['context'];
    

    至:

    $result->context;
    
  • 176

    使用 true 作为 json_decode 的第二个参数 . 这会将json解码为关联数组而不是 stdObject 实例:

    $my_array = json_decode($my_json, true);
    

    有关详细信息,请参阅the documentation .

  • 4

    今天有同样的问题,这样解决了:

    如果您调用 json_decode($somestring) ,您将获得一个Object,您需要访问 $object->key ,但是如果您调用 json_decode($somestring, true) ,您将获得一个字典,并且可以像 $array['key'] 一样访问

  • 2

    它不是数组,它是stdClass类型的对象 .

    您可以像这样访问它:

    echo $oResult->context;
    

    更多信息:What is stdClass in PHP?

  • 4

    正如 Php Manual 所说,

    print_r - 打印有关变量的人类可读信息

    当我们使用 json_decode(); 时,我们得到一个stdClass类型的对象作为返回类型 . 要在 print_r() 内传递的参数应该是数组或字符串 . 因此,我们无法传递 print_r() 内的对象 . 我找到了两种方法来解决这个问题 .

    • Cast the object to array.
      这可以如下实现 .
    $a = (array)$object;
    
    • By accessing the key of the Object
      如前所述,当您使用 json_decode(); 函数时,它返回一个stdClass的Object . 您可以在 -> Operator的帮助下访问对象的元素 .
    $value = $object->key;
    

    一,如果对象具有嵌套数组,也可以使用多个键来提取子元素 .

    $value = $object->key1->key2->key3...;
    

    他们也是 print_r() 的其他选择,如 var_dump();var_export();

    P.S :另外,如果将 json_decode(); 的第二个参数设置为 true ,它会自动将对象转换为 array();
    Here are some references:
    http://php.net/manual/en/function.print-r.php
    http://php.net/manual/en/function.var-dump.php
    http://php.net/manual/en/function.var-export.php

  • 119

    您可以将stdClass对象转换为数组,如:

    $array = (array)$stdClass;
    

    stdClsss to array

  • 20

    这是函数签名:

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

    当param为false(默认值)时,它将返回适当的php类型 . 您使用object.method范例获取该类型的值 .

    当param为true时,它将返回关联数组 .

    它会在出错时返回NULL .

    如果要通过数组获取值,请将assoc设置为true .

  • 645

    当你尝试以 $result['context'] 的形式访问它时,你将它视为一个数组,它告诉你实际上正在处理一个对象的错误,那么你应该以 $result->context 的形式访问它

  • 58

    而不是使用括号使用对象运算符,例如,基于数据库对象的数组在名为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;
    }
    
    }
    

    访问我在控制器脚本上使用此代码的信息:

    <?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';
    
    
    
    ?>
    

    然后显示我检查的信息,看看是否已设置servicecalls并且计数大于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'; ?>
    
  • 0

    我突然得到了这个错误,因为我的facebook登录突然停止工作(我也更改了主机)并抛出了这个错误 . 修复非常简单

    问题在于此代码

    $response = (new FacebookRequest(
        FacebookSession::newAppSession($this->appId, $this->appSecret),
        'GET',
        '/oauth/access_token',
        $params
      ))->execute()->getResponse(true);
    
      if (isset($response['access_token'])) {       <---- this line gave error
        return new FacebookSession($response['access_token']);
      }
    

    基本上isset()函数期望一个数组,但它找到一个对象 . 简单的解决方案是使用 (array) 量词将PHP对象转换为数组 . 以下是固定代码 .

    $response = (array) (new FacebookRequest(
        FacebookSession::newAppSession($this->appId, $this->appSecret),
        'GET',
        '/oauth/access_token',
        $params
      ))->execute()->getResponse(true);
    

    Note the use off array() quantifier in first line.

  • 2

    改变它

    $results->fetch_array()
    

相关问题