本文介绍了是否可以用较少的代码从值列为PHP中的数组元素分配键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个元素数组,这些元素本身就是数组,就像这样:
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'],
];
要将foo
字段的值设置为数组的键,我可以这样做:
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.
推荐答案
注意 array-column
也可以获取索引(第三个参数):
Notice array-column
can get index as well (third argument):
因此只需用作:
array_column($array, null, 'foo');
这篇关于是否可以用较少的代码从值列为PHP中的数组元素分配键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!