Search code examples
phparrayscodeigniterresultset

Populate a flat array from a single column of a CodeIgniter query


I have a database table with two columns (id and val) and I want to generate a simple array from the val values.

array('value', 'value2', 'value3'...); 

I have

$query = $this->db->query('SELECT val FROM table');
printf($query->result_array());

But it will result something like that:

Array
(
  [0] => Array
  (
    [val] => value
  )
  [1] => Array
  (
    [val] => value2
  )
)

How can I accumulate the val values as a flat array?


Solution

  • $query = $this->db->query('SELECT val FROM table')->result_array();
    
    $array = array();
    
    foreach ( $query as $key => $val )
    {
        $temp = array_values($val);
        $array[] = $temp[0];
    }
    

    See it here in action: http://viper-7.com/tPd7zN