【问题标题】:Remove only the whitespaces in array but not the 0(Zero) number仅删除数组中的空格,但不删除 0(零)数字
【发布时间】:2019-07-03 02:35:51
【问题描述】:

所以我试图删除多维数组中的空格。但整数 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
)"

【问题讨论】:

标签: php arrays


【解决方案1】:

您可以在 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

【讨论】:

  • 我无法实现 foreach 函数,但我使用了 array_filter( $v, 'strlen' );它奏效了!!!谢谢。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多