简体   繁体   English

php array_filter没有密钥保存

[英]php array_filter without key preservation

if i filter an array with array_filter to eliminate null values, keys are preserved and this generated "holes" in the array. 如果我使用array_filter过滤数组以消除空值,则会保留密钥并在数组中生成“漏洞”。 Eg: 例如:

The filtered version of
    [0] => 'foo'
    [1] =>  null
    [2] => 'bar'
is 
    [0] => 'foo'
    [2] => 'bar'

How can i get, instead 相反,我怎么能得到

[0] => 'foo'
[1] => 'bar'

?

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

Using this input: 使用此输入:

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

There are a few ways you could do it. 有几种方法可以做到。 Demo 演示

It's slightly off-topic to bring up array_filter 's greedy default behavior, but if you are googling to this page, this is probably important information relevant to your project/task: 提出array_filter的贪婪默认行为略显偏离主题,但是如果你正在搜索这个页面,这可能是与你的项目/任务相关的重要信息:

var_export(array_values(array_filter($array)));  // NOT GOOD!!!!!

Bad Output: 输出不好:

array (
  0 => 'foo',
  1 => 'bar',
)

Now for the ways that will work: 现在的方法将起作用:

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

var_export(array_values(array_filter($array,function($v){return !is_null($v);})));  // good

Method #2 : ( foreach() , auto-indexed array, !==null ) 方法#2 :( foreach() ,自动索引数组, !==null

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

Method #3 : ( array_walk() , auto-index array, !is_null() ) 方法#3 :( array_walk() ,自动索引数组, !is_null()

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

All three methods provide the following "null-free" output: 这三种方法都提供以下“无空”输出:

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => false,
  4 => '0',
  5 => '',
)

From PHP7.4, you can even perform a "repack" like this: (the splat operator requires numeric keys) 从PHP7.4开始,你甚至可以执行这样的“重新包装”:( splat操作符需要数字键)

Code: ( Demo ) 代码:( 演示

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

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

var_export($array);

Output: 输出:

array (
  0 => 'foo',
  1 => 'bar',
)

... but as it turns out, "repacking" with the splat operator is far less efficient than calling array_values() . ...但事实证明,使用splat运算符“重新打包”远比调用array_values() 效率低得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM