简体   繁体   English

从二维数组的子数组中删除“列”

[英]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. 我正在尝试编写一个有效的函数,它将返回一个只包含每个子数组的第一个'n'列的数组。 In other words, if n=2, then the returned array would be: 换句话说,如果n = 2,那么返回的数组将是:

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:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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