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(),但这不会起作用,因为这是一个多维数组!
Question
How can I create an array with the values of a specific key (name
) from another multi-dimensional array?
如何使用来自另一个多维数组的特定键(名称)的值创建数组?
3 个解决方案
#1
27
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
#2
9
This can be done in still more simple way by using array_coulmn
这可以通过使用array_coulmn以更简单的方式完成
$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用于获取子数组的列。
#3
3
$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 )
#1
27
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
#2
9
This can be done in still more simple way by using array_coulmn
这可以通过使用array_coulmn以更简单的方式完成
$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用于获取子数组的列。
#3
3
$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 )