CodeIgniter Forums
Cannot use object of type stdClass as array - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Cannot use object of type stdClass as array (/showthread.php?tid=41646)



Cannot use object of type stdClass as array - El Forum - 05-13-2011

[eluser]xerosis[/eluser]
In my controller I am calling a model which takes data from a database:
Code:
$spec_info = $this->spec_model->GetSpecs(array("id" => $this->input->post('image_spec_id')), 'width, height');
            
echo $spec_info['width'];

This ends up with the error: "Cannot use object of type stdClass as array"

How am I supposed to write it so it works?

Below is the code for my spec_model
Code:
function GetSpecs($options = array(), $require = NULL)
    {
        
        // Rows needed
        if(isset($require))
        {
            $this->db->select($require);
        }
        
        // Qualification
        foreach (array('id', 'title', 'width', 'height', 'w_text_count', 'h_text_count', 'created_on', 'last_activity', 'status') as $field)
        {
               if (isset($options[$field])) $this->db->where($field, $options[$field]);
        }

        // limit / offset
        if(isset($options['limit']) && isset($options['offset']))
            $this->db->limit($options['limit'], $options['offset']);
        else if(isset($options['limit']))
            $this->db->limit($options['limit']);
            
        // sort
        if(isset($options['sortBy']) && isset($options['sortDirection']))
            $this->db->order_by($options['sortBy'], $options['sortDirection']);
            
        if(!isset($options['status'])) $this->db->where('status !=', 'deleted');
        
        $query = $this->db->get("spec");
        
        if(isset($options['count'])) return $query->num_rows();
        
        if(isset($options['id']))
            return $query->row(0);
            
        return $query->result();
    }



Cannot use object of type stdClass as array - El Forum - 05-13-2011

[eluser]toopay[/eluser]
two option,

return the array instead object, on your model
Code:
return $query->result_array();
or on your controller
Code:
$spec_info = (array) $this->spec_model->GetSpecs(array("id" => $this->input->post('image_spec_id')), 'width, height');



Cannot use object of type stdClass as array - El Forum - 05-13-2011

[eluser]toopay[/eluser]
For better understanding, you may want to read types in php : http://www.php.net/manual/en/language.types.php