Best way to delete “column” from multidimensional array

狂风中的少年 提交于 2019-11-27 02:15:23

问题


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?


回答1:


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).




回答2:


The PHP manual for array_walk() states (emphasis added):

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

That sounds to me as if mpyw's and Amade's answer might work but cannot be relied on.

A safer solution might be the following:

function delete_col(&$array, $key)
{
    // Check that the column ($key) to be deleted exists in all rows before attempting delete
    foreach ($array as &$row)   { if (!array_key_exists($key, $row)) { return false; } }
    foreach ($array as &$row)   { unset($row[$key]); }

    unset($row);

    return true;
}


来源:https://stackoverflow.com/questions/16564650/best-way-to-delete-column-from-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!