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?

1
  • 1
    $newArray = array_combine(array_keys($records), array_column($records, 'first_name')); Commented Jun 20, 2017 at 13:55

3 Answers 3

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;
)()
Sign up to request clarification or add additional context in comments.

Comments

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');

1 Comment

Sorry, I should have made it clear - the desired data isn't available in the arrays, only as the key.
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',
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.