从各子阵列获取特定元素 [英] Get specific element from each sub array
问题描述
我有我敢肯定,必须有PHP处理内置阵列功能的通用模式,但只是无法看到它。
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.
我有多个阵列,如以下内容:
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"
)
);
我需要从每个子阵列,其中可以有任意数量获得键1
值。
我总是最后只是遍历每个阵列来获得所需的值,但我敢肯定,必须有处理这一个更简单,更有效的方式。
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.
我目前使用下面这个简单的foreach解析数组:
I am currently using the following simple foreach to parse the arrays:
$preparedSubs = array();
foreach($testArray as $subArray) {
$preparedSubs[] = $subArray['key1'];
}
这是短,我能做好,但正如我所说,我肯定有一个PHP的构造,将处理这更好的。
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 5.5之前,这将是最有效的解决方案:
Before PHP 5.5, this would be the most efficient solution:
$key = 'key1';
$output = array_map(function($item) use ($key) {
return $item[$key];
}, $testArray);
在PHP 5.5中,有现在是一个 array_column
函数这个(见的线圈的回答)。
这篇关于从各子阵列获取特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!