如何按条件过滤数组 [英] How to filter an array by a condition
本文介绍了如何按条件过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数组:
array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
现在我想通过某种条件过滤该数组,只保留值等于 2 的元素并删除值不是 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.
所以我的预期结果数组是:
So my expected result array would be:
array("a" => 2, "c" => 2, "f" => 2)
注意:我想保留原始数组中的键.
我怎样才能用 PHP 做到这一点?有什么内置函数吗?
How can I do that with PHP? Any built-in functions?
推荐答案
$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";
}
这篇关于如何按条件过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文