php 从每个子数组中获取特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10268337/
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
Get specific element from each sub array
提问by Marty Wallace
I have a common pattern which Im sure there must be a built-in array function in PHP to handle but just can't see it.
我有一个常见的模式,我确信 PHP 中必须有一个内置的数组函数来处理,但就是看不到它。
I have multiple arrays such as the following:
我有多个数组,如下所示:
$testArray = array (
'subArray1' => array(
'key1' => "Sub array 1 value 1",
'key2' => "Sub array 1 value 1"
),
'subArray2' => array(
'key1' => "Sub array 2 value 1",
'key2' => "Sub array 2 value 2"
)
);
I need to get the key1values from each subArray, of which there can be any number.
我需要key1从每个子数组中获取值,其中可以有任意数量。
I always end up just looping over each array to get the required values, but I'm sure there must be an easier, more efficient way to handle this.
我总是最终只是遍历每个数组以获得所需的值,但我确信必须有一种更简单、更有效的方法来处理这个问题。
I am currently using the following simple foreach to parse the arrays:
我目前正在使用以下简单的 foreach 来解析数组:
$preparedSubs = array();
foreach($testArray as $subArray) {
$preparedSubs[] = $subArray['key1'];
}
It's as short as I can make it, but as I said I'm sure there is a PHP construct that would handle this better.
它尽可能短,但正如我所说,我确信有一个 PHP 结构可以更好地处理这个问题。
回答by cmbuckley
Before PHP 5.5, this would be the most efficient solution:
在 PHP 5.5 之前,这将是最有效的解决方案:
$key = 'key1';
$output = array_map(function($item) use ($key) {
return $item[$key];
}, $testArray);
As of PHP 5.5, there is now an array_columnfunction for this (see COil's answer).
从 PHP 5.5 开始,现在有一个array_column用于此的函数(请参阅COil 的回答)。
回答by COil
As of PHP 5.5 you can use the array_column()function:
从 PHP 5.5 开始,您可以使用array_column()函数:
$key = 'key1';
$testArray = array (
'subArray1' => array(
'key1' => "Sub array 1 value 1",
'key2' => "Sub array 1 value 2"
),
'subArray2' => array(
'key1' => "Sub array 2 value 1",
'key2' => "Sub array 2 value 2"
)
);
$output = array_column($testArray, $key);
var_dump($output);
Will output:
将输出:
array(2) {
[0]=>
string(19) "Sub array 1 value 1"
[1]=>
string(19) "Sub array 2 value 1"
}
The only difference with the accepted answer is that you lose the original key name, but I think this is not a problem in your case.
与接受的答案的唯一区别是您丢失了原始密钥名称,但我认为这对您来说不是问题。

