I wrote a simple function array_column_keys
that has the same parameters as array_column
.
/**
* Return the values from a single column in the input array by keeping the key
*
* @param array $array A multi-dimensional array (record set) from which to pull a column of values.
* @param mixed $column The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).
* @param mixed $index_key [optional] The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.
*
* @return array Returns an array of values representing a single column from the input array.
*/
function array_column_keys($array, $column, $index_key = null)
{
$output = [];
foreach ($array as $key => $item) {
$output[@$item[$index_key] ?? $key] = @$item[$column];
}
return array_filter($output, function($item) {
return null !== $item;
});
}
The third parameter index_key
is what I also needed.
This will answer the question when setting third parameter to null
as in following example:
$result = array_column_keys($items, 'id');
...and also let's you define the value for the key
$result = array_column_keys($items, 'id', 'any_key');
This will result in
array (size=3)
string 'any_value1' => int 5
string 'any_value2' => int 6
string 'any_value3' => int 7