php array_filter没有密钥保存

pis*_*hio 38 php arrays

如果我使用array_filter过滤数组以消除空值,则会保留密钥并在数组中生成"漏洞".例如:

The filtered version of
    [0] => 'foo'
    [1] =>  null
    [2] => 'bar'
is 
    [0] => 'foo'
    [2] => 'bar'
Run Code Online (Sandbox Code Playgroud)

相反,我怎么能得到

[0] => 'foo'
[1] => 'bar'
Run Code Online (Sandbox Code Playgroud)

Gum*_*mbo 76

您可以array_values在过滤后使用以获取值.


mic*_*usa 10

使用此输入:

$array=['foo',NULL,'bar',0,false,null,'0',''];
Run Code Online (Sandbox Code Playgroud)

有几种方法可以做到这一点。演示

提出 的贪婪默认行为有点偏离主题array_filter,但如果您在谷歌上搜索此页面,这可能是与您的项目/任务相关的重要信息:

var_export(array_values(array_filter($array)));  // NOT GOOD!!!!!
Run Code Online (Sandbox Code Playgroud)

不良输出:

array (
  0 => 'foo',
  1 => 'bar',
)
Run Code Online (Sandbox Code Playgroud)

现在介绍可行的方法:

方法#1:( array_values(), array_filter()w/ !is_null())

var_export(array_values(array_filter($array,function($v){return !is_null($v);})));  // good
Run Code Online (Sandbox Code Playgroud)

方法 #2 : ( foreach(), 自动索引数组, !==null)

foreach($array as $v){
    if($v!==null){$result[]=$v;}
}
var_export($result);  // good
Run Code Online (Sandbox Code Playgroud)

方法 #3 : ( array_walk(), 自动索引数组, !is_null())

array_walk($array,function($v)use(&$filtered){if(!is_null($v)){$filtered[]=$v;}});
var_export($filtered);  // good
Run Code Online (Sandbox Code Playgroud)

所有三种方法都提供以下“无空”输出:

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => false,
  4 => '0',
  5 => '',
)
Run Code Online (Sandbox Code Playgroud)

从 PHP7.4 开始,您甚至可以像这样执行“重新打包”:(splat 运算符需要数字键)

代码:(演示

$array = ['foo', NULL, 'bar', 0, false, null, '0', ''];

$array = [...array_filter($array)];

var_export($array);
Run Code Online (Sandbox Code Playgroud)

输出:

array (
  0 => 'foo',
  1 => 'bar',
)
Run Code Online (Sandbox Code Playgroud)

...但事实证明,使用 splat 运算符“重新打包”的效率远低于调用array_values().