Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to delete "column" from multidimensional array

I have a multidimensional php array that represents a table like this

-------------
| A | 0 | A |
|---|---|---|
| 0 | 0 | 0 |
|---|---|---|
| A | 0 | A |
-------------

so the array looks like this:

array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)
  1 => 
    array (size=3)
      0 => string '0' (length=1)
      1 => string '0' (length=1)
      2 => string '0' (length=1)
  2 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string '0' (length=1)
      2 => string 'A' (length=1)

Now i want to delete the second row and the second column (this is just a simplified example btw).
Deleting the row is easy:

array_splice($array, 1, 1);

I found this approach but was wondering if there was a simpler way (similar to the row) of deleting the column as well? Maybe transposing the array first?

like image 722
Horen Avatar asked May 15 '13 12:05

Horen


People also ask

How to delete a column in 2d array in c?

You can not remove a column from an array. But you can move all elements of columns to the left filling the "deleted" column and keep the number of actual columns of the array.

How to delete column in NumPy array?

Using the NumPy function np. delete() , you can delete any row and column from the NumPy array ndarray . Specify the axis (dimension) and position (row number, column number, etc.). It is also possible to select multiple rows and columns using a slice or a list.

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 [] .

What is a multidimensional array?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.


1 Answers

Try this:

function delete_row(&$array, $offset) {
    return array_splice($array, $offset, 1);
}

function delete_col(&$array, $offset) {
    return array_walk($array, function (&$v) use ($offset) {
        array_splice($v, $offset, 1);
    });
}

Tested on Ideone: http://ideone.com/G5zRi0

Edit (Amade):

delete_col function can also be slightly modified to work with arrays with missing columns:

function delete_col(&$array, $key) {
    return array_walk($array, function (&$v) use ($key) {
        unset($v[$key]);
    });
}

This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).

like image 100
mpyw Avatar answered Sep 24 '22 11:09

mpyw