[英]How can I create an array from the values of another array's key?
I have an array as follows: 我有一个数组如下:
$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');
I have looked at array_filter()
, but that would not work as this is a multi-dimensional array! 我看过
array_filter()
,但这不会起作用,因为这是一个多维数组!
How can I create an array with the values of a specific key ( name
) from another multi-dimensional array? 如何使用来自另一个多维数组的特定键(
name
)的值创建数组?
Newer versions of PHP allow using array_map()
with a function expression instead of a function name: 较新版本的PHP允许使用带有函数表达式而不是函数名的
array_map()
:
$arr2 = array_map(function($person) {
return $person['name'];
}, $arr1);
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. 但是如果使用PHP <5.3,则使用简单循环要容易得多,因为
array_map()
需要为这个简单的操作定义一个(可能是全局的)函数。
$arr2 = array();
foreach ($arr1 as $person) {
$arr2[] = $person['name'];
}
// $arr2 now contains all names
This can be done in still more simple way by using array_column 这可以通过使用array_column以更简单的方式完成
$arr2= array_column($arr1, 'name');
print_r($arr2); //Array ( [0] => tom [1] => nick )
array_column is used to get the columns of a sub-array. array_column用于获取子数组的列。
$array = array(0 => array('name' => 'tom', 'age' => 22), 1 => array('name' => 'nick', 'age' => 18));
foreach($array as $arr => $a){
$names[] = $array[$arr]["name"];
}
print_r($names); //Array ( [0] => tom [1] => nick )
如果您使用的是Laravel,那么只需使用array_pluck
:
$arr2 = array_pluck($arr1 , 'name');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.