让数组值不foreach循环 [英] getting array values without foreach loop
问题描述
有没有办法让在一个阵列中的所有值,而无需使用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"]);
我需要的输出是阵列(A,B,C)
我可以用这样的完成它
$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'));
如果您使用的是previous PHP版本,目前无法升级,您可以使用的用户空间实施 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屋!