PHP - unset in a multidimensional array

▼魔方 西西 提交于 2019-12-17 12:48:08

问题


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

回答1:


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

foreach(array_keys($output) as $key) {
   unset($output[$key][1]);
}



回答2:


You can iterate over the array, and unset() what you want in each sub-array:

foreach($output as &$item) {
    unset($item[2]);
}
unset($item); // unset reference



回答3:


Clean and neat:

$f=function(&$a,$k) { unset $a[1]; };
array_walk($arr,$f);



回答4:


You'd use a combination of array_map and array_splice:

function removeSecond( array &$arr )
{
    array_splice( $arr, 1, 1 );
}
$out = array_map( 'removeSecond', $input );

The problem with unset is that it will leave the indexes as they were:

$ php -r '$arr = array(array(0,1,2)); unset($arr[0][1]); var_dump($arr);'
array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(0)
    [2]=>
    int(2)
  }
}

While splice will update the indexes:

$ php -r '$arr = array(array(0,1,2)); array_splice($arr[0], 1, 1); var_dump($arr);'
array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(0)
    [1]=>
    int(2)
  }
}



回答5:


foreach($array as $key=>$val){ unset($val[1]); }


来源:https://stackoverflow.com/questions/7260468/php-unset-in-a-multidimensional-array

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