如何获得特定“键"的数组.在多维数组中而不循环 [英] How to get an array of specific "key" in multidimensional array without looping
问题描述
假设我具有以下多维数组(从MySQL或服务检索):
Let's assume I have the following multidimensional array (retrieved from MySQL or a service):
array(
array(
[id] => xxx,
[name] => blah
),
array(
[id] => yyy,
[name] => blahblah
),
array(
[id] => zzz,
[name] => blahblahblah
),
)
我们可以在一个"内置" php函数调用中获得一个由id
组成的数组吗?或一行代码?
我知道传统的循环并获得价值,但我不需要这个:
Can we get an array of id
s in one "built-in" php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don't need this:
foreach($users as $user) {
$ids[] = $user['id'];
}
print_r($ids);
也许某些array_map()
和call_user_func_array()
可以发挥作用.
Maybe some array_map()
and call_user_func_array()
can do the magic.
推荐答案
从php 5.5开始,您可以使用 array_column
:
Since php 5.5, you can use array_column
:
$ids = array_column($users, 'id');
这是任何现代项目的首选选项.但是,如果必须支持php> 5.5,则存在以下替代方法:
This is the preferred option on any modern project. However, if you must support php > 5.5, the following alternatives exist:
从php 5.3开始,您可以将 array_map
与匿名函数,如下所示:
Since php 5.3, you can use array_map
with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
在 (技术上为php 4.0.6 +) 之前,您必须使用
这篇关于如何获得特定“键"的数组.在多维数组中而不循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!