如何按条件过滤数组

men*_*mam 24 php arrays filter higher-order-functions

我有这样一个数组:

array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
Run Code Online (Sandbox Code Playgroud)

现在我想通过某种条件过滤该数组,只保留值等于2的元素,并删除值为2的所有元素.

所以我期望的结果数组是:

array("a" => 2, "c" => 2, "f" => 2)
Run Code Online (Sandbox Code Playgroud)

注意:我想保留原始数组中的键.

我怎么能用PHP做到这一点?任何内置功能?

Sim*_*mon 49

$fullarray = array('a'=>2,'b'=>4,'c'=>2,'d'=>5,'e'=>6,'f'=>2);


function filterArray($value){
    return ($value == 2);
}

$filteredArray = array_filter($fullArray, 'filterArray');

foreach($filteredArray as $k => $v){
    echo "$k = $v";
}
Run Code Online (Sandbox Code Playgroud)

  • 最好更新此答案以使用闭包,以在2019年教授最佳实践! (2认同)

Gum*_*mbo 24

你不得不循环遍历你的数组并根据你的条件过滤每个元素.这可以通过各种方法完成.

循环while/ for/ foreach方法

使用您想要的任何循环遍历您的数组,可能是while,forforeach.然后只需检查您的状况以及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
}
Run Code Online (Sandbox Code Playgroud)

条件

只需将您的条件放入注释所在的循环中即可//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
}

Run Code Online (Sandbox Code Playgroud)

array_filter() 方法

另一种方法是使用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);
Run Code Online (Sandbox Code Playgroud)

preg_grep() 方法

preg_grep()类似于array_filter()它只使用正则表达式来过滤数组.因此,您可能无法使用它执行所有操作,因为您只能使用正则表达式作为过滤器,并且您只能按值过滤或使用更多代码按键过滤.

另请注意,您可以将标志PREG_GREP_INVERT作为第三个参数传递以反转结果.

//Filter by values
$newArray = preg_grep("/regex/", $array);
Run Code Online (Sandbox Code Playgroud)

常见情况

有许多常用条件用于过滤数组,其中所有数组都可以应用于数组的值和/或键.我将在这里列出其中一些:

//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 'empty'(link) values
array_filter($array);  //Leave out the callback parameter
Run Code Online (Sandbox Code Playgroud)

  • @Simon:手册不仅适用于书虫.所有开发人员都应该能够足够聪明地阅读它.但也许大多数人都希望复制和粘贴示例,他们不必考虑. (2认同)