7

I have a simple, two dimensional array like this:

Array
    (
        [0] => Array
            (
                [0] => abc
                [1] => 123
                [2] => aaaaa

            )

        [1] => Array
            (
                [0] => def
                [1] => 456
                [2] => ddddd
            )

        [2] => Array
            (
                [0] => ghi
                [1] => 789
                [2] => hhhhhhh
            )
    )

I'm trying to write an efficient function which will return an array with only the first 'n' columns of each subarray. In other words, if n=2, then the returned array would be:

Array
    (
        [0] => Array
            (
                [0] => abc
                [1] => 123


            )

        [1] => Array
            (
                [0] => def
                [1] => 456

            )

        [2] => Array
            (
                [0] => ghi
                [1] => 789

            )
    )
NikiC
  • 100,734
  • 37
  • 191
  • 225
jalperin
  • 2,664
  • 9
  • 30
  • 32

4 Answers4

17
const MAX = 2; // maximum number of elements
foreach ($array as &$element) {
    $element = array_slice($element, 0, MAX);
}
NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 1
    @hopeseekr: You're right `&$element` is available as of PHP 5. For some reason I thought it was introduced in PHP 5.3. – NikiC Sep 13 '10 at 16:59
0

Even with array_walk :

array_walk(
    $aYourArray,
    function(&$aSubRow){
        $aSubRow = array_slice($aSubRow, 0, 2);
    }
);
Arsham
  • 1,432
  • 3
  • 19
  • 28
0
foreach($array as $key=> $element)
{
    for($i=0; $i<$n; $i++)
    {
        $newArray[$key][$i] = $element[$i];
    }
}

Not sure if there is a more efficient method.

Gazler
  • 83,029
  • 18
  • 279
  • 245
0

Anything wrong with just looping through it?

for ( $i = 0; $i < sizeof($input); $i++ ) {
    for ( $j = 0; $j < $n; $j++ ) {
        $output[$i][$j] = $input[$i][$j];
    }
}
return $output;
JCD
  • 2,211
  • 1
  • 19
  • 29