问题
Let's assume I have an array of elements, which are arrays themselves, like so:
$array = [
['foo' => 'ABC', 'bar' => 'DEF'],
['foo' => 'ABB', 'bar' => 'DDD'],
['foo' => 'BAC', 'bar' => 'EFF'],
];
To set the values of the foo field as the key of the array I could do this:
foreach ($array as $element) {
$new_array[$element['foo']] = $element;
}
$array = $new_array;
The code is naturally trivial, but I've been wondering whether there's an in-built that can do the same for me.
回答1:
Notice array-column can get index as well (third argument):
mixed $index_key = NULL
So just use as:
array_column($array, null, 'foo');
回答2:
Here is one liner for your case,
$temp = array_combine(array_column($array, 'foo'), $array);
Working demo.
array_combine — Creates an array by using one array for keys and another for its values
array_column — Return the values from a single column in the input array
回答3:
You can also do it with array_reduce
$new_array = array_reduce($array, function($carry, $item) {
$carry[$item['foo']] = $item;
return $carry;
}, []);
来源:https://stackoverflow.com/questions/56108051/is-it-possible-to-assign-keys-to-array-elements-in-php-from-a-value-column-with