如何从另一个数组的键的值创建一个数组? [英] How can I create an array from the values of another array's key?

查看:113
本文介绍了如何从另一个数组的键的值创建一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下数组:

$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

这篇关于如何从另一个数组的键的值创建一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆