您必须以某种方式遍历您的数组并根据您的条件过滤每个元素。这可以通过多种方法来完成。
用任何你想要的循环遍历你的数组,可以是while、for 或foreach。然后只需检查您的条件,如果元素不满足您的条件,则可以unset() 或将满足条件的元素写入新数组。
循环
//while loop
while(list($key, $value) = each($array)){
//condition
}
//for loop
$keys = array_keys($array);
for($counter = 0, $length = count($array); $counter < $length; $counter++){
$key = $keys[$counter];
$value = $array[$key];
//condition
}
//foreach loop
foreach($array as $key => $value){
//condition
}
条件
只需将您的条件放入注释//condition 所在的循环中即可。条件可以只检查您想要的任何内容,然后您可以unset() 不满足您的条件的元素,如果需要,可以使用array_values() 重新索引数组,或者将元素写入符合条件的新数组中条件。
//Pseudo code
//Use one of the two ways
if(condition){ //1. Condition fulfilled
$newArray[ ] = $value;
//↑ Put '$key' there, if you want to keep the original keys
//Result array is: $newArray
} else { //2. Condition NOT fulfilled
unset($array[$key]);
//Use array_values() after the loop if you want to reindex the array
//Result array is: $array
}
另一种方法是使用array_filter() 内置函数。它通常与使用简单循环的方法几乎相同。
如果要将元素保留在数组中,只需返回 TRUE,如果要将元素从结果数组中删除,则只需返回 FALSE。
//Anonymous function
$newArray = array_filter($array, function($value, $key){
//condition
}, ARRAY_FILTER_USE_BOTH);
//Function name passed as string
function filter($value, $key){
//condition
}
$newArray = array_filter($array, "filter", ARRAY_FILTER_USE_BOTH);
//'create_function()', NOT recommended
$newArray = array_filter($array, create_function('$value, $key', '/* condition */'), ARRAY_FILTER_USE_BOTH);
preg_grep() 与array_filter() 类似,只是它只使用正则表达式来过滤数组。所以你可能无法用它做所有事情,因为你只能使用正则表达式作为过滤器,你只能按值过滤或通过键使用更多代码。
还请注意,您可以将标志 PREG_GREP_INVERT 作为第三个参数传递以反转结果。
//Filter by values
$newArray = preg_grep("/regex/", $array);
常见情况
用于过滤数组的常用条件有很多,所有条件都可以应用于数组的值和/或键。我将在这里列出其中的一些:
//Odd values
return $value & 1;
//Even values
return !($value & 1);
//NOT null values
return !is_null($value);
//NOT 0 values
return $value !== 0;
//Contain certain value values
return strpos($value, $needle) !== FALSE; //Use 'use($needle)' to get the var into scope
//Contain certain substring at position values
return substr($value, $position, $length) === $subString;
//NOT @987654328@ values
array_filter($array); //Leave out the callback parameter