1

Suppose I have an array of records, keyed by some ID, and I use the array_column() function to extract one piece of data from each record.

$records = array(
    1234 => array(
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    4567 => array(
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
);

The result from array_column($input, 'first_name') is a numerically indexed array (with new keys 0, 1, ...). Is there a way of keeping the keys from the input array?

jeromegamez
  • 3,348
  • 1
  • 23
  • 36
joachim
  • 28,554
  • 13
  • 41
  • 44

3 Answers3

1
array_map(function ($r) { return $r['first_name']; }, $records)

will do (for your precise case).

It is more or less equivalent to this (PHP 7+):

(function () use ($records) {
    $result = [];
    foreach ($records as $key => $r) {
        $result[$key] = $r['first_name'];
    }
    return $result;
)()
0

When the id would also be available in the data array's you could use the third argument of array_column.

For example: array_column($records, 'first_name', 'id');

Giso Stallenberg
  • 942
  • 7
  • 10
  • 2
    Sorry, I should have made it clear - the desired data isn't available in the arrays, only as the key. – joachim Jun 21 '17 at 15:52
0

Here's a simple function I often use:

function array_column_with_keys(array $array, string $column): array {
    return array_combine(
        array_keys($array), 
        array_column($array, $column));
}

So using your example array,

var_export(array_column_with_keys($records, 'first_name'));

will return:

array (
  1234 => 'John',
  4567 => 'Sally',
)
pbarney
  • 2,529
  • 4
  • 35
  • 49