10

I have a multidimensional array, that has say, x number of columns and y number of rows.

I want specifically all the values in the 3rd column.

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];
}

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]
4

5 回答 5

28

给定一个二维数组$channels

$channels = array(
    array(
        'id' => 100,
        'name' => 'Direct'
    ),
    array(
        'id' => 200,
        'name' => 'Dynamic'
    )
);

一个不错的方法是使用array_map

$_currentChannels = array_map(function ($value) {
    return  $value['name'];
}, $channels);

如果你是一个通过array_column的权威(php 5.5+) :

$_currentChannels = array_column($channels, 'name');

两者都导致:

Array
(
    [0] => Direct
    [1] => Dynamic
)

明星嘉宾: array_map (php4+) 和array_column (php5.5+)

// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
于 2014-10-02T20:12:57.363 回答
3

是否有一种内置方法可以让我简单地从数组中提取这些行中的每一行而无需循环。

还没有。很快就会有一个名为array_column(). 但是复杂性是一样的,只是优化了一点,因为它是用 C 和 PHP 引擎实现的。

于 2013-06-18T07:32:55.393 回答
0

Another way to do the same would be something like $newArray = array_map( function($a) { return $a['desiredColumn']; }, $oldArray ); though I don't think it will make any significant (if any) improvement on the performance.

于 2013-06-18T22:38:29.537 回答
0

尝试这个....

   foreach ($array as $val)
   {
       $thirdCol[] = $val[2];
   }

你最终会得到一个包含第三列所有值的数组

于 2013-06-18T01:01:58.807 回答
-2

你可以试试这个:

$array["a"][0]=10;
$array["a"][1]=20;
$array["a"][2]=30;
$array["a"][3]=40;
$array["a"][4]=50;
$array["a"][5]=60;

$array["b"][0]="xx";
$array["b"][1]="yy";
$array["b"][2]="zz";
$array["b"][3]="aa";
$array["b"][4]="vv";
$array["b"][5]="rr";

$output = array_slice($array["b"], 0, count($array["b"]));

print_r($output);
于 2013-06-18T01:04:21.787 回答