[FIXED] Isolate a single column in a multi-dimensional array

Issue

Say for example you just queried a database and you recieved this 2D array.

$results = array(
    array('id' => 1, 'name' => 'red'  , 'spin' =>  1),
    array('id' => 2, 'name' => 'green', 'spin' => -1),
    array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);

I often find myself writing loops like this.

foreach($results as $result)
    $names[] = $result['name'];

My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.

Here is a more generic example of getting every field.

foreach($results as $result)
    foreach($result as $key => $value)
        $fields[$key][] = $value;

Solution

As of June 20th in PHP-5.5 there is a new function array_column

For example:

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe'
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith'
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones'
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe'
    )
);


$firstNames = array_column($records, 'first_name');
print_r($firstNames);

Will return

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

There are even more examples in the above mentioned link.

Answered By – Salvador Dali

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published