php 如何从另一个数组的键的值创建一个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4550976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:25:49  来源:igfitidea点击:

How can I create an array from the values of another array's key?

phparray-filter

提问by newbtophp

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?

如何使用name来自另一个多维数组的特定键 ( )的值创建数组?

回答by jwueller

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

回答by JVT

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 用于获取子数组的列。

回答by Dejan Marjanovic

$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 ) 

回答by Usama

if you are using Laravel, then simply use array_pluck:

如果您使用的是 Laravel,那么只需使用array_pluck

$arr2 = array_pluck($arr1 , 'name');