4

I'm using a query in Codeigniter to return the ids of all the rows that belong to a user.

$this->db->select('id');
$this->db->where('user_id', 99);
$query = $this->db->get('my_table');
return $query->result_array();

This returns

Array ( [0] => Array ( [id] => 8 ) [1] => Array ( [id] => 7 ) [2] => Array ( [id] => 6 ) )

Is it possible to return a flat array like

Array ( [0] => 8 [1] => 6 [2] => 7 )

?

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

2 Answers2

8

The CodeIgniter documentation (most particularly, query results) doesn't list anything that will produce a flat array result (like the PDO::FETCH_COLUMN mode provided for PDOStatement::fetchAll). As such, array results will need to be flattened in your code, such as with a foreach loop:

$flat = array();
foreach($query->result_array() as $row) {
    $flat[] = $row['id'];
}

or with the special purpose array_column:

array_column($query->result_array(), 'id');

or with the general purpose array_reduce:

array_reduce(
    $results, 
    fn ($accum, $row) => array_merge($accum, [$row['id']]),
    []);

If you're to lazy to add few lines each time you select one column, you would need to tweak CodeIgniter. Like adding some option or returning flattened array when single column is selected. I would suggest adding an option

outis
  • 75,655
  • 22
  • 151
  • 221
Minimihi
  • 408
  • 2
  • 11
  • 1
    Thanks! I was hoping that codeignter had a built in function. – CyberJunkie Sep 22 '12 at 17:26
  • Wouldn't it be better to store the result of the function in a variable rather than calling the function each for loop? – user2019515 May 26 '13 at 03:41
  • Unless modifying by reference, `foreach()` "makes a copy" and plays with that. As a consequence of that behavior, the `result_array()` method is not called iteratively. @user2019515 – mickmackusa Oct 10 '19 at 00:13
0

Following can be another way of dong it. I don't know what is the advantage of it over the accepted answer.

Let's say you are storing output of function in $result. Then you can do as following:

array_unshift($result, null);
$transposed = call_user_func_array("array_map", $result);
print_r($transposed);

It will print

Array( [0] => Array ( [0] => 8 [1] => 6 [2] => 7 ))

And you can access what you want by $transposed[0]

Array ( [0] => 8 [1] => 6 [2] => 7 )

dikesh
  • 2,977
  • 2
  • 16
  • 26