Is it possible to assign keys to array elements in PHP from a value column with less code?

陌路散爱 提交于 2020-05-09 06:16:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!