php数组array_filter
<?php $arr = [ 'a' => 'aa', 'b' => 0, 'c' => '', ];
//直接用默认过滤函数 print_r(array_filter($arr));
//自定义过滤函数 function test ($var) { if ($var !== '' && $var != null) {//注意 $var != null return 1; } return 0; } $res = array_filter($arr,'test'); print_r($res);
//传入闭包函数 $res = array_filter($arr, function ($var) {//注意 $var !== null if ($var !== '' && $var !== null) { return true; } return false; } ); print_r($res);
//传入类的过滤函数 class ClsMy{ public function test ($var) { if ($var !== '' && $var !== null) { return 4; } return false; } } $cls = new ClsMy(); $res = array_filter($arr,[$cls,'test']);//注意[$cls,'test'] print_r($res); ?>
输出
Array
(
[a] => aa
)
Array
(
[a] => aa
)
Array
(
[a] => aa
[b] => 0
)
Array
(
[a] => aa
[b] => 0
)