Wednesday 29 August 2012

Reduce PHP array or arrays with keys to just their values

Note: If you are using PHP5.5+ then ignore the rest of this post. You should use array_column() instead.

When you are running a query to get data from a database table like this using a framework like CodeIgniter with code like this:

$result = $this->db->select('id')->from('table')->order_by('field_n')->get()->result_array();

The $result tends to look something like this:

$result = array(
    array('id' => 1),
    array('id' => 2),
    array('id' => 3),
    ...
);

What I would like is an array of values like this:

$result = array(1, 2, 3);

I've found a good way to achieve this is to run this code (PHP5.3+):

$result = array_map(function($v){return array_shift($v);}, $result);

Doing a print_r of $result shows the code produces the flat array we want:

Array(
    [0] => 1,
    [1] => 2,
    [2] => 3,
    ...
);

There is also an added benefit in that we can select which field we want to return if there is more than one column in the table. Consider the following query:

$result = $this->db->select('id','name')->from('table')->order_by('name')->get()->result_array();

which puts these values into results:

$result = array(
    array('id' => 3, 'name' => 'Aaron'),
    array('id' => 1, 'name' => 'Brian'),
    array('id' => 2, 'name' => 'Steve'),
    ...
);

What if we just want to get the names from the array? Here's the code and the output:

$result = array_map(function($v){return $v['name'];}, $result);

Array(
    [0] => 'Aaron',
    [1] => 'Brian',
    [2] => 'Steve',
    ...
);

1 comment:

  1. very good descreption it useful for php developer.If you want to get data from a database table in php .you are see this Articles it is very helpful to you.

    ReplyDelete