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?
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.
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.
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 [] .
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With