0

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?

2 Answers 2

2
$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

Sign up to request clarification or add additional context in comments.

1 Comment

Your demo appears to be expired/empty.
0

Use one of CodeIgniter's 2d array populating methods (e.g. result() or result_array()) then call array_column() on that structure.

return array_column($this->db->get('my_table')->result(), 'val');

This will isolate the val column values as a flat, indexed array.

If the result set from the query is empty, the array from array_column() will also be empty.

Use a select() method if you like:

return array_column($this->db->select('val')->get('my_table')->result(), 'val');

Populate an associative array where the id column becomes keys and the val column becomes values.

return array_column($this->db->get('my_table')->result(), 'val', 'id');

or

return array_column($this->db->select('id, val')->get('my_table')->result(), 'val', 'id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.