Search code examples
phpcodeigniteractiverecord

Codeigniter: Produce Array instead of Object in Active Record


I want Codeigniter produce array result in active record, just like mysql_fetch_array() does in standard PHP.

Let's just say, we have this table in our mysql database, called students.

+-----+------+
| id  | name |
+-----+------+
|  1  | Elto |
|  2  | John |
+------------+

This is the conditions.
I generate the query in separated way. It's Just like :

$this->db->select('id, name');
$this->db->order_by('name', 'asc');
$q = $this->db->get('students');
$r = $q->result();

$r will produce:

[0] (name => 'Elto')
[1] (name => 'John')

Instead of that, I want the query produce something like this:

[0][0] => 'Elto'
[1][0] => 'John'

I don't know if this can be done. If anyone wants to help this problem, I would be very grateful.


Solution

  • You just need to use result_array() instead of result():

    $this->db->select('id, name');
    $this->db->order_by('name', 'asc');
    $q = $this->db->get('students');
    $r = $q->result_array();
    

    result() will return you rows in Object format.

    result_array() will return you rows into array format.

    Please explore CodeIgniter Generating Query Results