Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

            )
    )
like image 233
jalperin Avatar asked Sep 13 '10 16:09

jalperin


People also ask

How to remove an array from a 2D array in Python?

Python Numpy: Delete elements from a 2D arrayUsing the NumPy method np. delete(), you can delete any row and column from the NumPy array ndarray. We can also remove elements from a 2D array using the numpy delete() function.


1 Answers

const MAX = 2; // maximum number of elements
foreach ($array as &$element) {
    $element = array_slice($element, 0, MAX);
}
like image 140
NikiC Avatar answered Oct 05 '22 11:10

NikiC