问题描述
我有一个多维数组,也就是说,x 列数和 y 行数.
I have a multidimensional array, that has say, x number of columns and y number of rows.
我特别想要第 3 列中的所有值.
I want specifically all the values in the 3rd column.
最明显的方法是把它放在像这样的 for 循环中
The obvious way to go about doing this is to put this in a for loop like this
for(i=0;i<y-1;i++)
{
$ThirdColumn[] = $array[$i][3];
}
但是这里明显涉及 O(n) 的时间复杂度.是否有一种内置方法可以让我简单地从数组中提取这些行中的每一行而无需循环.
but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
例如(这在课外不起作用)
For example (this does not work offcourse)
$ThirdColumn = $array[][3]
推荐答案
给定一个二维数组 $channels
:
$channels = array(
array(
'id' => 100,
'name' => 'Direct'
),
array(
'id' => 200,
'name' => 'Dynamic'
)
);
一个不错的方法是使用array_map:
A nice way is using array_map:
$_currentChannels = array_map(function ($value) {
return $value['name'];
}, $channels);
如果你是一个通过 array_column 的当权者 (php 5.5+):
and if you are a potentate (php 5.5+) through array_column:
$_currentChannels = array_column($channels, 'name');
两个结果:
Array
(
[0] => Direct
[1] => Dynamic
)
明星嘉宾:array_map (php4+) 和 array_column (php5.5+)
Star guests:array_map (php4+) and array_column (php5.5+)
// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
这篇关于获取多维数组中特定列的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!