|
|
 |
array_filter (PHP 4 >= 4.0.6, PHP 5) array_filter --
用回调函数过滤数组中的单元
说明array array_filter ( array input [, callback function])
array_filter() 依次将
input 数组中的每个值传递到
callback 函数。如果
callback 函数返回 TRUE,则
input
数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。
例子 1. array_filter() 例子 |
<?php
function odd($var) {
return ($var % 2 == 1);
}
function even($var) {
return ($var % 2 == 0);
}
$array1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>
|
以上程序的输出为:
|
Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)
|
|
用户不应在回调函数中修改数组本身。例如增加/删除单元或者对
array_filter() 正在作用的数组进行
unset。如果数组改变了,此函数的行为没有定义。
参见 array_map(),array_reduce()
和 array_walk()。
sam,pointsystems,com
21-Feb-2002 09:12
Here's a good function to filter multidimensional
arrays:
<?php
function array_filter_multi($input,
$filter="", $keepMatches=true) {
if
(!is_array($input))
return ($input==$filter xor
$keepMatches==false) ? $input : false;
while (list
($key,$value) = @each($input)){
$res =
array_filter_multi($value, $filter,$keepMatches);
if
($res !== false)
$out[$key] = $res;
}
return $out;
}
?>
Default behavior is to
remove blanks from a multi-dimensional array, but you can filter out any
string (arg #2) with a positive or negative filter (arg #3).
| |