php 在没有 foreach 循环的情况下获取数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22760538/
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
getting array values without foreach loop
提问by iOi
Is there any way to get all values in one array without using foreach loops, in this example?
在这个例子中,有没有办法在不使用 foreach 循环的情况下获取一个数组中的所有值?
<?php
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);
The output I need is array("a", "b", "c")
我需要的输出是 array("a", "b", "c")
I could accomplish it using something like this
我可以使用这样的东西来完成它
$stack = [];
foreach($foo as $value){
$stack[] = $value["type"];
}
var_dump($stack);
But, I am looking for options that does not involve using foreach loops.
但是,我正在寻找不涉及使用 foreach 循环的选项。
回答by Amal Murali
If you're using PHP 5.5+, you can use array_column()
, like so:
如果您使用的是 PHP 5.5+,则可以使用array_column()
,如下所示:
$result = array_column($foo, 'type');
If you want an array with numeric indices, use:
如果你想要一个带有数字索引的数组,请使用:
$result = array_values(array_column($foo, 'type'));
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.
如果您使用的是以前的 PHP 版本并且目前无法升级,则可以使用由同一作者编写的array_column()
函数的Userland 实现。
Alternatively, you could also use array_map()
. This is basically the same as a loop except that the looping is not explicitly shown.
或者,您也可以使用array_map()
. 除了没有明确显示循环之外,这与循环基本相同。
$result = array_map(function($arr) {
return $arr['type'];
}, $foo);
回答by Alma Do
Either use array_column()
for PHP 5.5:
要么array_column()
用于 PHP 5.5:
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);
$result = array_column($foo, 'type');
Or use array_map()
for previous versions:
或array_map()
用于以前的版本:
$result = array_map(function($x)
{
return $x['type'];
}, $foo);
Note: The loop will still be performed, but it will be hidden inside the aforementioned functions.
注意:循环仍然会执行,但它会隐藏在上述函数中。