如何从另一个数组的键的值创建一个数组?
我有一个如下数组:
$arr1 = array(
0 => array(
'name' => 'tom',
'age' => 22
),
1 => array(
'name' => 'nick',
'age' => 18
)
);
但是我想从中创建一个包含所有名称的数组,因此它将变成:
However I want to create an array from it which consists of all the names, so it would become:
$arr2 = array('tom', 'nick');
我看过 array_filter()
,但这不起作用,因为这是一个多维数组!
I have looked at array_filter()
, but that would not work as this is a multi-dimensional array!
如何创建一个数组与另一个多维数组中的特定键(名称
)的值?
How can I create an array with the values of a specific key (name
) from another multi-dimensional array?
较新版本的PHP允许使用 array_map()
使用函数表达式而不是函数名称:
Newer versions of PHP allow using array_map()
with a function expression instead of a function name:
$arr2 = array_map(function($person) {
return $person['name'];
}, $arr1);
但是如果您使用的是PHP< 5.3中,使用简单的循环要容易得多,因为 array_map()
需要为此简单的操作定义一个(可能是全局的)函数。
But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map()
would require to define a (probably global) function for this simple operation.
$arr2 = array();
foreach ($arr1 as $person) {
$arr2[] = $person['name'];
}
// $arr2 now contains all names