PHP - 删除多维数组中的元素

时间:2014-01-21 04:12:17

标签: arrays multidimensional-array elements

我有这个数组:

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

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

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

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

)

并且需要删除(取消设置?)所有值为“c”的元素,以便最终得到:

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

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

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

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

)

元素被删除,其他元素向上移动。我知道unset不会重新索引数组。无法为所有多维数组取消设置,但只能使用一个数组。之后可以重新索引数组吗?欣赏它。

代码BELOW删除值等于“c”的元素,但不重新索引第一个元素的索引。任何人都可以建议重新索引内部数组的解决方案吗?

$i=0;
foreach ($array as $val)
    {
    foreach ($val as $key => $final_val)
        { 

        if ($final_val =="$search_value") 
            {
             unset($array[$i][$key]);
            }
        } 
    i = $i + 1;
    }

2 个答案:

答案 0 :(得分:6)

以下代码将执行您想要的操作:

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

输出:

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
        )

)

如你所见,所有3已经消失......

答案 1 :(得分:1)

搜索子数组中的值然后取消设置。

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

或者您也可以使用循环:

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