PHP - unset in a multidimensional array

后端 未结 5 394
长发绾君心
长发绾君心 2020-12-03 17:17

I have this array $output which looks like this:

Array(
    [0] => Array(
        [0] => 1a
        [1] => 1b
        [2] => 1c
    )
    [1] =&g         


        
相关标签:
5条回答
  • 2020-12-03 17:59

    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)
      }
    }
    
    0 讨论(0)
  • 2020-12-03 18:07

    Clean and neat:

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

    Or:

    array_walk($arr, function (&$a, $k) {
      unset($a[1]); 
    });
    
    0 讨论(0)
  • 2020-12-03 18:08

    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
    
    0 讨论(0)
  • 2020-12-03 18:20

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

    foreach(array_keys($output) as $key) {
       unset($output[$key][1]);
    }
    
    0 讨论(0)
  • 2020-12-03 18:24
    foreach($array as $key=>$val){ unset($val[1]); }
    
    0 讨论(0)
提交回复
热议问题