简体   繁体   中英

Remove “columns” from the subarrays of a two dimensional array

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

            )
    )
const MAX = 2; // maximum number of elements
foreach ($array as &$element) {
    $element = array_slice($element, 0, MAX);
}

Even with array_walk :

array_walk(
    $aYourArray,
    function(&$aSubRow){
        $aSubRow = array_slice($aSubRow, 0, 2);
    }
);
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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM