Best way to delete “column” from multidimensional array

你离开我真会死。 提交于 2019-11-28 08:29:41
mpyw

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

Tanathon

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