在没有 foreach 循环的情况下获取数组值 [英] getting array values without foreach loop

查看:50
本文介绍了在没有 foreach 循环的情况下获取数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,有没有办法在不使用 foreach 循环的情况下获取一个数组中的所有值?

Is there any way to get all values in one array without using foreach loops, in this example?

<?php 
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);

我需要的输出是array("a", "b", "c")

我可以用这样的东西来完成它

I could accomplish it using something like this

$stack = [];

foreach($foo as $value){
  $stack[] = $value["type"];
}

var_dump($stack); 

但是,我正在寻找不涉及使用 foreach 循环的选项.

But, I am looking for options that does not involve using foreach loops.

推荐答案

如果你使用的是 PHP 5.5+,你可以使用 array_column(),像这样:

If you're using PHP 5.5+, you can use array_column(), like so:

$result = array_column($foo, 'type');

如果你想要一个带有数字索引的数组,请使用:

If you want an array with numeric indices, use:

$result = array_values(array_column($foo, 'type'));

如果您使用的是以前的 PHP 版本并且目前无法升级,您可以使用 Userland 实现同一作者写的array_column()函数.

If you're using a previous PHP version and can't upgrade at the moment, you can use the Userland implementation of array_column() function written by the same author.

或者,您也可以使用 array_map().除了没有明确显示循环之外,这与循环基本相同.

Alternatively, you could also use array_map(). This is basically the same as a loop except that the looping is not explicitly shown.

$result = array_map(function($arr) {
   return $arr['type'];
}, $foo);

这篇关于在没有 foreach 循环的情况下获取数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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