Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset a column in a multidimensional array

I have this array $output which looks like this:

Array(
    [0] => Array(
        [0] => 1a
        [1] => 1b
        [2] => 1c
    )
    [1] => Array(
        [0] => 2a
        [1] => 2b
        [2] => 2c
    )
    [2] => Array(
        [0] => 3a
        [1] => 3b
        [2] => 3c
    )
    [3] => Array(
        [0] => 4a
        [1] => 4b
        [2] => 4c
    )
)

and so on...

When I want to remove the second element I just use:

$output = unset($output[1]);

to get the following:

Array(
    [0] => Array(
        [0] => 1a
        [1] => 1b
        [2] => 1c
    )
    [1] => Array(
        [0] => 3a
        [1] => 3b
        [2] => 3c
    )
    [2] => Array(
        [0] => 4a
        [1] => 4b
        [2] => 4c
    )
)

My question is how to remove every second element of every element in the array ([0][1], [1][1], [2][1], [3][1] ,...) to get the following:

Array(
    [0] => Array(
        [0] => 1a
        [1] => 1c
    )
    [1] => Array(
        [0] => 2a
        [1] => 2c
    )
    [2] => Array(
        [0] => 3a
        [1] => 3c
    )
    [3] => Array(
        [0] => 4a
        [1] => 4c
    )
)
like image 304
Giel Avatar asked Aug 31 '11 16:08

Giel


People also ask

How do you delete a column from an array in Matlab?

The easiest way to remove a row or column from a matrix is to set that row or column equal to a pair of empty square brackets [] .

How do you unset an array key?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.


1 Answers

Can't be done with a simple command, but you can use a loop:

foreach(array_keys($output) as $key) {
   unset($output[$key][1]);
}
like image 160
Marc B Avatar answered Oct 16 '22 22:10

Marc B