0
foreach ($arr as $key => $value) {
    foreach ($arr_ as $key_ => $value_) {
        $dev[$value_][] = array_search($value_, $arr[$key]);
    }
}

我需要从数组搜索中排除所有布尔值 false,但保留原始键。所以,这就是我想要的 AAAA。我怎样才能做到这一点?

'AAAA' => 
        array
          1 => int 0
          3 => int 1
          5 => int 1
          7 => int 2
          9 => int 1
          11 => int 2
          13 => int 2
          15 => int 3

我有的:

array
  'AAAA' => 
    array
      0 => boolean false
      1 => int 0
      2 => boolean false
      3 => int 1
      4 => boolean false
      5 => int 1
      6 => boolean false
      7 => int 2
      8 => boolean false
      9 => int 1
      10 => boolean false
      11 => int 2
      12 => boolean false
      13 => int 2
      14 => boolean false
      15 => int 3
  'BBBB' => 
    array
      0 => boolean false
      1 => boolean false
      2 => int 0
      3 => int 0
      4 => boolean false
      5 => boolean false
      6 => int 1
      7 => int 1
      8 => boolean false
      9 => boolean false
      10 => int 1
      11 => int 1
      12 => boolean false
      13 => boolean false
      14 => int 2
      15 => int 2
  'CCCC' => 
    array
      0 => boolean false
     ....
4

4 回答 4

3

对于单个数组,您可以使用:

foreach($array as $key => $element) {
    if($element === false) {
        unset($array[$key]);
    }
}

然后只需将其包装在另一个 foreach 循环中以处理其他循环(注意参考&$array):

foreach($arrays as &$array) {
    foreach($array as $key => $element) {
        if($element === false) {
            unset($array[$key]);
        }
    }
}
于 2013-09-30T21:16:32.177 回答
1
$arr = array(false,0,false,1,false,2,false,0,false);
$out = array_filter($arr, function($in) { return false !== $in; });
var_dump($out);

输出:

array(4) {
  [1]=>
  int(0)
  [3]=>
  int(1)
  [5]=>
  int(2)
  [7]=>
  int(0)
}
于 2013-09-30T21:22:19.617 回答
0

使用array_filter,它保存原始密钥php.net: array_filter

$newArr=array_filter($oldArr, function($el) { return $el !== false; })
于 2013-09-30T21:19:08.517 回答
0

在此处查看此答案:从数组中删除元素

您可以使用 unset() 来保留由 if 语句触发的键(if false) { unset($array[$index]) } etc

于 2013-09-30T21:17:26.973 回答