dkregen
dkregen

Reputation: 477

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.

Upvotes: 0

Views: 1302

Answers (4)

mickmackusa
mickmackusa

Reputation: 47971

To ensure that not only the first level contains indexed arrays, but also that each row contains indexed elements, apply a numeric alias to the name column in your SELECT statement and then use result_array() or getResultArray() (depending on your CI version).

Depending on your database driver, the alias quoting character may vary. Tested on my application running firebird, double quoting the numeric alias rendered properly.

return $this->db
            ->select('name AS "0"')
            ->order_by('name', 'ASC')
            ->get('students')
            ->result_array();

Will return an indexed array of single-element, indexed arrays.

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

Upvotes: 0

TV-C-1-5
TV-C-1-5

Reputation: 714

Codeigniter 4:

$r = $q->getResultArray();

Upvotes: 0

devpro
devpro

Reputation: 16117

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

Upvotes: 2

Peter Black Moore
Peter Black Moore

Reputation: 92

You can use

$r = $q->result_array();

or you can use

$r = $q->row_array(); 

To retrive only one item.

Check offical documentation for more information:

http://www.codeigniter.com/user_guide/database/results.html

Regards.

Upvotes: 1

Related Questions