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

时间:2011-07-25 11:40:15

标签: php json

我使用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']其中$result包含json_decode()

返回的数据

如何读取此数组中的值?

16 个答案:

答案 0 :(得分:693)

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

$result = json_decode($data, true);

答案 1 :(得分:187)

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

您可以访问以下数据:

var_dump($result->context);

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

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

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

$result = json_decode($json, true);

或者将对象转换为数组:

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

答案 2 :(得分:129)

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

更改您的代码:

$result['context'];

要:

$result->context;

答案 3 :(得分:78)

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

$my_array = json_decode($my_json, true);

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

答案 4 :(得分:75)

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

如果您致电json_decode($somestring),您将获得一个对象,并且您需要访问$object->key,但如果您拨打json_decode($somestring, true),您将获得一个字典,并且可以访问$array['key'] }

答案 5 :(得分:56)

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

你可以像这样访问它:

echo $oResult->context;

此处有更多信息:What is stdClass in PHP?

答案 6 :(得分:23)

正如 Php手册所说,

  

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

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

  1. 将对象投射到数组。
    这可以通过以下方式实现。

    $a = (array)$object;
    
  2. 访问对象的键
    如前所述,当您使用json_decode();函数时,它返回一个stdClass的Object。您可以在->运算符的帮助下访问对象的元素。

    $value = $object->key;
    
  3. 一,如果对象具有嵌套数组,也可以使用多个键来提取子元素。

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

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

    PS :此外,如果您将json_decode();的第二个参数设置为true,它会自动将对象转换为array(); 以下是一些参考资料:
    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

答案 7 :(得分:10)

有时使用API​​时,您只想将一个对象保留为一个对象。要访问具有嵌套对象的对象,您可以执行以下操作:

我们假设当您打印对象时,您可能会看到以下内容:

print_r($response);

stdClass object
(
    [status] => success
    [message] => Some message from the data
    [0] => stdClass object
        (
            [first] => Robert
            [last] => Saylor
            [title] => Symfony Developer
        )
    [1] => stdClass object
        (
            [country] => USA
        )
)

要访问对象的第一部分:

print $response->{'status'};

这将输出“成功”

现在让我们锁定其他部分:

$first = $response->{0}->{'first'};
print "First name: {$first}<br>";

预期的输出将是带有换行符的“罗伯特”。

您还可以将对象的一部分重新分配给另一个对象。

$contact = $response->{0};
print "First Name: " . $contact->{'first'} . "<br>";

预期的输出将是带有换行符的“罗伯特”。

要访问下一个键“ 1”,过程相同。

print "Country: " . $response->{1}->{'country'} . "<br>";

预期输出为“美国”

希望这将帮助您了解对象以及为什么我们要将对象保留为对象。您无需将对象转换为数组即可访问其属性。

答案 8 :(得分:9)

试试这个!

而不是像这样获取上下文:(这适用于获取数组索引)

$result['context']

尝试(这项工作用于获取对象)

$result->context

其他示例是:(如果 $result 有多个数据值)

Array
(
    [0] => stdClass Object
        (
            [id] => 15
            [name] => 1 Pc Meal
            [context] => 5
            [restaurant_id] => 2
            [items] => 
            [details] => 1 Thigh (or 2 Drums) along with Taters
            [nutrition_fact] => {"":""}
            [servings] => menu
            [availability] => 1
            [has_discount] => {"menu":0}
            [price] => {"menu":"8.03"}
            [discounted_price] => {"menu":""}
            [thumbnail] => YPenWSkFZm2BrJT4637o.jpg
            [slug] => 1-pc-meal
            [created_at] => 1612290600
            [updated_at] => 1612463400
        )

)

然后试试这个:

foreach($result as $results)
{
      $results->context;
}

答案 9 :(得分:7)

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

$array = (array)$stdClass;

stdClsss to array

答案 10 :(得分:5)

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

答案 11 :(得分:4)

这是函数签名:

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

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

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

错误时将返回NULL。

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

答案 12 :(得分:2)

而不是使用括号使用对象运算符,例如基于数据库对象的数组在名为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,记住它不是我引用的数组,所以我使用对象运算符“ - &gt;”访问记录像这样:

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

答案 13 :(得分:2)

我突然得到了这个错误,因为我的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()函数需要一个数组,而是找到一个对象。简单的解决方案是使用(数组)量词将PHP对象转换为数组。以下是固定代码。

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

注意在第一行使用off array()量词。

答案 14 :(得分:2)

要从json字符串获取数组作为结果,应将第二个参数设置为boolean true。

$result = json_decode($json_string, true);
$context = $result['context'];

否则$ result将是一个std对象。但是您可以将值作为对象访问。

  $result = json_decode($json_string);
 $context = $result->context;

答案 15 :(得分:0)

将其更改为

$results->fetch_array()
相关问题