Home > Article > Backend Development > Someone helped me write an array filter function that can pass parameters. How to use it?
This is to delete the items less than 123 in the array.
I did an experiment and the result didn’t work. How can I change it?
Learn and study the elements of the array that will not be deleted...
<code>$arr = Array(1 , 2 , 3713231987,3710001690,3713182016,3714441990,3713231932); user_array_filter($arr, 'myGt' , 123 ) ; echo '<pre class="brush:php;toolbar:false">';print_r($arr);echo ''; function user_array_filter( &$array, $callback ) { $args = func_get_args(); //把function 所有参数保存成数组; if( count($args) < 2 ) exit('function user_array_filter()参数错误 , 最少有两个参数.'); if( count($args) == 2 ) { foreach( $array as $k => $v ) { $result = $callback($v); if( !$result ) { return false;//★★★★★★★★★★★★★★★★★★★★★★ } } } else { $limit = $args[2]; // [0]->处理数组 , [1]->function , [2]->value foreach( $array as $k => $v ) { $result = $callback($v, $limit); if( !$result ) { return false;//★★★★★★★★★★★★★★★★★★★★★★ } } } } function myGt($val, $limit = 88){ if ($val >= $limit) return true; return false; }
This is to delete the items less than 123 in the array.
I did an experiment and the result didn’t work. How can I change it?
Learn and study the elements of the array that will not be deleted...
<code>$arr = Array(1 , 2 , 3713231987,3710001690,3713182016,3714441990,3713231932); user_array_filter($arr, 'myGt' , 123 ) ; echo '<pre class="brush:php;toolbar:false">';print_r($arr);echo ''; function user_array_filter( &$array, $callback ) { $args = func_get_args(); //把function 所有参数保存成数组; if( count($args) < 2 ) exit('function user_array_filter()参数错误 , 最少有两个参数.'); if( count($args) == 2 ) { foreach( $array as $k => $v ) { $result = $callback($v); if( !$result ) { return false;//★★★★★★★★★★★★★★★★★★★★★★ } } } else { $limit = $args[2]; // [0]->处理数组 , [1]->function , [2]->value foreach( $array as $k => $v ) { $result = $callback($v, $limit); if( !$result ) { return false;//★★★★★★★★★★★★★★★★★★★★★★ } } } } function myGt($val, $limit = 88){ if ($val >= $limit) return true; return false; }
Change else in user_array_filter to the following code
<code> else { $limit = $args[2]; // [0]->处理数组 , [1]->function , [2]->value foreach( $array as $k => $v ) { $result = $callback($v, $limit); if( !$result ) { unset($array[$k]); } } } </code>
ps: If you want to delete array elements, you can foreach the array and then unset() the entire key if the conditions are not met in the loop