PHP - remove element in multidimensional array

前端 未结 2 722
無奈伤痛
無奈伤痛 2020-12-19 11:41

I have this array:

Array ( 
[0] => Array ( [0] => b [1] => d [2] => **c** [3] =>a [4] => ) 

[1] => Array ( [0] => **c** [1] => a          


        
相关标签:
2条回答
  • 2020-12-19 11:43

    Search the value in the sub array then unset it.

    $search = 'c';
    $result = array_map(function ($value) use ($search) {
       if(($key = array_search($search, $value)) !== false) {
          unset($value[$key]);
       }
       return $value;
    }, $your_array);
    

    Or you could use a loop too:

    // this way change your original array
    foreach ($your_array as &$sub_array) {
        if(($key = array_search($search, $sub_array)) !== false) {
            unset($sub_array[$key]);
        }
    }
    var_dump($your_array);
    
    0 讨论(0)
  • 2020-12-19 12:08

    The following code will do what you want:

    <?php
    $a = 1;
    $b = 2;
    $c = 3;
    $d = 4;
    
    $arr = array(
    array ( $b, $d, $c, $a, $b),
    array ($c, $a),
    array ( $b, $d,  $c ),
    array( $c, $d, $a, $b, $b)
    );
    echo "before:\n";
    print_r($arr);
    
    foreach($arr as $k1=>$q) {
      foreach($q as $k2=>$r) {
        if($r == $c) {
          unset($arr[$k1][$k2]);
        }
      }
    }
    echo "after:\n";
    print_r($arr);
    ?>
    

    Output:

    before:
    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 4
                [2] => 3
                [3] => 1
                [4] => 2
            )
    
        [1] => Array
            (
                [0] => 3
                [1] => 1
            )
    
        [2] => Array
            (
                [0] => 2
                [1] => 4
                [2] => 3
            )
    
        [3] => Array
            (
                [0] => 3
                [1] => 4
                [2] => 1
                [3] => 2
                [4] => 2
            )
    
    )
    after:
    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 4
                [3] => 1
                [4] => 2
            )
    
        [1] => Array
            (
                [1] => 1
            )
    
        [2] => Array
            (
                [0] => 2
                [1] => 4
            )
    
        [3] => Array
            (
                [1] => 4
                [2] => 1
                [3] => 2
                [4] => 2
            )
    
    )
    

    As you can see, all the 3's have gone...

    0 讨论(0)
提交回复
热议问题