首页 > 解决方案 > 仅删除数组中的空格,但不删除 0(零)数字

问题描述

所以我试图删除多维数组中的空格。但整数 0 包含在删除中。

我已经尝试过 array_filter 和 array_map 来删除它。

$a="array(
      [0] => test
      [1] => 0
      [2] => test
      [3] => 
      [4] => 
      [5] => test
)
array(
      [0] => test
      [1] => 
      [2] => 
      [3] => 
      [4] => 0
      [5] => test
)"
$b=array_filter(array_map('trim', $a));
print_r($b);

输出是

"array(
      [0] => test
      [2] => test
      [5] => test
)
array(
      [0] => test
      [5] => test
)"

但是预期的输出应该是这样的

"array(
      [0] => test
      [1] => 0
      [2] => test
      [5] => test
)
array(
      [0] => test
      [4] => 0
      [5] => test
)"

标签: phparrays

解决方案


你可以在和的帮助下array_filter()strlen

$result = [];
foreach($a as $k=>$v){
    // strlen will remove all NULL, FALSE and empty strings but leaves 0 values
    $result[$k] =  array_filter( $v, 'strlen' );
}
print_r($result);

工作演示: https ://3v4l.org/chq3D


推荐阅读