【问题标题】:php- Fatal Error: Cannot use object of type stdClass as arrayphp-致命错误:不能使用 stdClass 类型的对象作为数组
【发布时间】:2017-03-04 10:49:04
【问题描述】:
    $store_list = array();
    $this->db->select('user_time');
    $this->db->from('users');
    $this->db->where('staff_id',$userid);
    $result = $this->db->get();

    $result= $result->result();
    foreach($result as $rows){
        array_push($store_list, $rows["user_time"]);
    }
    return $store_list;

我在一个模型中编写了一个函数,其中包含上述代码,当用户的 id 作为参数传递时,它会获取用户的时间,并将用户的时间返回给控制器函数。

但我收到以下错误:Fatal Error: Cannot use object of type stdClass as array

是什么导致了这个错误?有什么想法吗?

注意:sql 查询返回所有匹配的记录。它可以是一条或多条记录。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    可能是$result它是对象而不是数组,这样使用

    array_push($store_list, $rows->user_time);
    

    【讨论】:

    • 用户这个 $result = $this->db->get()->result_array();
    • 在使用这样的 foreach 循环之前也要进行检查 if ($result) { foreach..... }
    【解决方案2】:

    错误是因为

    $result= $result->result();
    

    这里$result 是一个标准类对象,要访问它的元素使用-> 而不是[] 像:

    array_push($store_list, $rows->user_time);
    

    或者像数组一样使用它:

    $result = $this->db->get()->result_array();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 2014-07-18
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多