13

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]
Muc
  • 1,464
  • 2
  • 13
  • 31
Parijat Kalia
  • 4,929
  • 10
  • 50
  • 77

5 Answers5

32

Given a bidimensional array $channels:

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

A nice way is using array_map:

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

and if you are a potentate (php 5.5+) through array_column:

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

Both results in:

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

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 ] )
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
Igor Parra
  • 10,214
  • 10
  • 69
  • 101
3

Is there a built in way for me to simply extract each of these rows from the array without having to loop in.

Not yet. There will be a function soon named array_column(). However the complexity will be the same, it's just a bit more optimized because it's implemented in C and inside the PHP engine.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

Try this....

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

Youll endup with an array of all values from 3rd column

hakre
  • 193,403
  • 52
  • 435
  • 836
Kylie
  • 11,421
  • 11
  • 47
  • 78
  • 2
    this is off course, what I have stated in my post as the obvious way to go about doing it is by foreach looping, but thanks anyways – Parijat Kalia Jun 18 '13 at 01:08
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.

Muc
  • 1,464
  • 2
  • 13
  • 31
-2

You could try this:

$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);
1ry
  • 77
  • 10