php 如何按条件过滤数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1503579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter an array by a condition
提问by menardmam
I have an array like this:
我有一个这样的数组:
array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.
现在我想通过某种条件过滤该数组,只保留值等于 2 的元素并删除值不是 2 的所有元素。
So my expected result array would be:
所以我的预期结果数组是:
array("a" => 2, "c" => 2, "f" => 2)
Note: I want to keep the keys from the original array.
注意:我想保留原始数组中的键。
How can I do that with PHP? Any built-in functions?
我怎样才能用 PHP 做到这一点?有什么内置函数吗?
回答by Simon
$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";
}
回答by Gumbo
You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.
您必须以某种方式遍历数组并根据条件过滤每个元素。这可以通过各种方法来完成。
Loops while/ for/ foreachmethod
环路while/ for/foreach方法
Loop through your array with any loop you want, may it be while, foror foreach. Then simply check for your condition and either unset()the elements if they don't meet your condition or write the elements, which meet the condition, into a new array.
使用您想要的任何循环遍历您的数组,可能是while,for或foreach。然后只需检查您的条件和unset()元素,如果它们不满足您的条件,或者将满足条件的元素写入一个新数组。
Looping
循环
//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
健康)状况
Just place your condition into the loop where the comment //conditionis. The condition can just check for whatever you want and then you can either unset()the elements which don't meet your condition, and reindex the array with array_values()if you want, or write the elements in a new array which meet the 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()method
array_filter()方法
Another method is to use the array_filter()built-in function. It generally works pretty much the same as the method with a simple loop.
另一种方法是使用array_filter()内置函数。它通常与具有简单循环的方法几乎相同。
You just need to return TRUEif you want to keep the element in the array and FALSEif you want to drop the element out of the result array.
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()method
preg_grep()方法
preg_grep()is similar to array_filter()just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.
preg_grep()类似于array_filter()它只使用正则表达式来过滤数组。因此,您可能无法用它做所有事情,因为您只能使用正则表达式作为过滤器,并且您只能按值或按键使用更多代码进行过滤。
Also note that you can pass the flag PREG_GREP_INVERTas third parameter to invert the results.
另请注意,您可以将标志PREG_GREP_INVERT作为第三个参数传递以反转结果。
//Filter by values
$newArray = preg_grep("/regex/", $array);
Common conditions
常见情况
There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here:
有许多用于过滤数组的常见条件,所有条件都可以应用于数组的值和/或键。我将在这里列出其中的一些:
//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
回答by soulmerge
You can iterate on the copies of the keys to be able to use unset()in the loop:
您可以迭代密钥的副本以便能够unset()在循环中使用:
foreach (array_keys($array) as $key) {
if ($array[$key] != 2) {
unset($array[$key]);
}
}
The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.
如果您的数组包含大值,则此方法的优点是内存效率 - 它们不会重复。
EDITI just noticed, that you actually only need the keys that have a value of 2 (you already know the value):
编辑我刚刚注意到,您实际上只需要值为 2 的键(您已经知道该值):
$keys = array();
foreach ($array as $key => $value) {
if ($value == 2) {
$keys[] = $key;
}
}
回答by Tom Haigh
This should work, but I'm not sure how efficient it is as you probably end up copying a lot of data.
这应该可行,但我不确定它的效率如何,因为您最终可能会复制大量数据。
$newArray = array_intersect_key(
$fullarray,
array_flip(array_keys($fullarray, 2))
);
回答by mickmackusa
I think the snappiest, readable built-in function is: array_intersect()
我认为最快速、可读的内置函数是:array_intersect()
Code: (Demo)
代码:(演示)
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
var_export(array_intersect($array, [2]));
Output:
输出:
array (
'a' => 2,
'c' => 2,
'f' => 2,
)
Just make sure you declare the 2nd parameter as an array because that is the value type expected.
只需确保将第二个参数声明为数组,因为这是预期的值类型。
Now there is nothing wrong with writing out a foreach loop, or using array_filter(), they just have a more verbose syntax.
现在写出 foreach 循环或使用 没有错array_filter(),它们只是有更冗长的语法。
array_intersect()is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.
array_intersect()通过向第二个参数数组添加更多值,也很容易扩展(包括额外的“限定”值)。
回答by Goran Juri?
foreach ($aray as $key => $value) {
if (2 != $value) {
unset($array($key));
}
}
echo 'Items in array:' . count($array);
回答by Alex Mcp
I might do something like:
我可能会做这样的事情:
$newarray = array();
foreach ($jsonarray as $testelement){
if ($testelement == 2){$newarray[]=$testelement}
}
$result = count($newarray);

