How to use array_column to get particular key, value from multidimensional array

if you want to get particular value of particular key from an array then use array_column as per below:

<?php
$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',
           )
);

$first_names = array_column($records, 'first_name');
echo "<pre>";
print_r($first_names);
echo "</pre>";

$last_names = array_column($records, 'last_name', 'id');
echo "<pre>";
print_r($last_names);
echo "</pre>";
?>

Note: if you do not provide "index_key" then it will take numeric index, otherwise it will take "index_key" as you specified in array_column function.
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)


Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

Post a Comment

0 Comments