array_filter()是PHP中过滤数组的核心函数,通过回调函数实现灵活筛选,结合匿名函数和use关键字可构建动态条件,支持基于值、键或两者同时过滤,常与array_map、array_reduce等函数组合使用,形成“过滤-映射-聚合”的数据处理链,提升代码可读性与维护性。

在PHP中,对数组进行条件过滤的核心工具无疑是
array_filter()
use
array_filter()
true
false
最直接的用法,我们可以定义一个简单的函数作为回调:
function isEven($value) {
return $value % 2 === 0;
}
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, 'isEven');
print_r($evenNumbers);
// 输出: Array ( [1] => 2 [3] => 4 [5] => 6 )然而,当过滤条件需要依赖外部变量或更复杂的逻辑时,匿名函数(或称闭包)就显得尤为重要。通过
use
立即学习“PHP免费学习笔记(深入)”;
$threshold = 3;
$data = [1, 2, 3, 4, 5, 6];
// 过滤出大于 $threshold 的元素
$filteredData = array_filter($data, function($value) use ($threshold) {
return $value > $threshold;
});
print_r($filteredData);
// 输出: Array ( [3] => 4 [4] => 5 [5] => 6 )这只是冰山一角。
array_filter()
ARRAY_FILTER_USE_KEY
ARRAY_FILTER_USE_BOTH
array_filter()
$users = [
'john.doe' => ['age' => 30, 'active' => true],
'jane.smith' => ['age' => 25, 'active' => false],
'peter.jones' => ['age' => 40, 'active' => true]
];
// 过滤出用户名包含 'john' 的用户
$filteredByUsername = array_filter($users, function($key) {
return str_contains($key, 'john');
}, ARRAY_FILTER_USE_KEY);
print_r($filteredByUsername);
// 输出: Array ( [john.doe] => Array ( [age] => 30 [active] => 1 ) )
// 过滤出活跃且年龄大于35的用户
$activeOldUsers = array_filter($users, function($userData, $username) {
return $userData['active'] && $userData['age'] > 35;
}, ARRAY_FILTER_USE_BOTH);
print_r($activeOldUsers);
// 输出: Array ( [peter.jones] => Array ( [age] => 40 [active] => 1 ) )这种灵活性让
array_filter()
在我看来,
array_filter()
想象一下,你有一个商品列表,需要根据用户的搜索条件来筛选。这些条件(例如价格区间、品牌、库存状态)都是运行时决定的,你不可能为每一种组合都写一个独立的过滤函数。这时候,
use
$products = [
['name' => 'Laptop', 'price' => 1200, 'brand' => 'A', 'in_stock' => true],
['name' => 'Mouse', 'price' => 25, 'brand' => 'B', 'in_stock' => true],
['name' => 'Keyboard', 'price' => 75, 'brand' => 'A', 'in_stock' => false],
['name' => 'Monitor', 'price' => 300, 'brand' => 'C', 'in_stock' => true],
];
// 假设这是从用户输入或配置中获取的动态条件
$minPrice = 50;
$maxPrice = 500;
$targetBrand = 'A';
$mustBeInStock = true;
$filteredProducts = array_filter($products, function($product) use ($minPrice, $maxPrice, $targetBrand, $mustBeInStock) {
$priceCondition = $product['price'] >= $minPrice && $product['price'] <= $maxPrice;
$brandCondition = empty($targetBrand) || $product['brand'] === $targetBrand; // 如果没有指定品牌,则不进行品牌过滤
$stockCondition = !$mustBeInStock || $product['in_stock']; // 如果不需要库存条件,则不进行库存过滤
return $priceCondition && $brandCondition && $stockCondition;
});
print_r($filteredProducts);
/*
输出:
Array
(
[2] => Array
(
[name] => Keyboard
[price] => 75
[brand] => A
[in_stock] =>
)
)
*/这里,
$minPrice
$maxPrice
$targetBrand
$mustBeInStock
此外,别忘了
ARRAY_FILTER_USE_KEY
ARRAY_FILTER_USE_BOTH
array_filter()
array_filter()
array_map()
array_reduce()
array_walk()
array_filter()
一个常见的场景是“过滤后映射”(Filter then Map)。我们先筛选出符合特定条件的元素,然后对这些元素进行转换,提取出我们真正需要的信息。
$users = [
['id' => 1, 'name' => 'Alice', 'status' => 'active', 'email' => 'alice@example.com'],
['id' => 2, 'name' => 'Bob', 'status' => 'inactive', 'email' => 'bob@example.com'],
['id' => 3, 'name' => 'Charlie', 'status' => 'active', 'email' => 'charlie@example.com'],
];
// 1. 过滤出活跃用户
$activeUsers = array_filter($users, function($user) {
return $user['status'] === 'active';
});
// 2. 从活跃用户中提取他们的邮箱地址
$activeUserEmails = array_map(function($user) {
return $user['email'];
}, $activeUsers);
print_r($activeUserEmails);
// 输出: Array ( [0] => alice@example.com [1] => charlie@example.com )反过来,“映射后过滤”(Map then Filter)也是一种思路。有时,原始数据需要先经过某种计算或转换,才能形成可供过滤的条件。
$grades = [
['student' => 'A', 'scores' => [80, 90, 75]],
['student' => 'B', 'scores' => [60, 65, 70]],
['student' => 'C', 'scores' => [95, 88, 92]],
];
// 1. 计算每个学生的平均分,并添加到数组中
$gradesWithAverage = array_map(function($grade) {
$grade['average'] = array_sum($grade['scores']) / count($grade['scores']);
return $grade;
}, $grades);
// 2. 过滤出平均分大于80的学生
$highAchievers = array_filter($gradesWithAverage, function($grade) {
return $grade['average'] > 80;
});
print_r($highAchievers);
/*
输出:
Array
(
[0] => Array
(
[student] => A
[scores] => Array ( [0] => 80 [1] => 90 [2] => 75 )
[average] => 81.666666666667
)
[2] => Array
(
[student] => C
[scores] => Array ( [0] => 95 [1] => 88 [2] => 92 )
[average] => 91.666666666667
)
)
*/再比如,“过滤后聚合”(Filter then Reduce)。这适用于先筛选出感兴趣的数据子集,然后对这个子集进行统计或汇总。
$transactions = [
['id' => 1, 'amount' => 100, 'type' => 'sale', 'status' => 'completed'],
['id' => 2, 'amount' => 50, 'type' => 'refund', 'status' => 'completed'],
['id' => 3, 'amount' => 200, 'type' => 'sale', 'status' => 'pending'],
['id' => 4, 'amount' => 150, 'type' => 'sale', 'status' => 'completed'],
];
// 1. 过滤出已完成的销售交易
$completedSales = array_filter($transactions, function($transaction) {
return $transaction['type'] === 'sale' && $transaction['status'] === 'completed';
});
// 2. 计算这些销售的总金额
$totalSalesAmount = array_reduce($completedSales, function($carry, $item) {
return $carry + $item['amount'];
}, 0);
echo "总销售金额: " . $totalSalesAmount; // 输出: 总销售金额: 250这种组合使用的方式,不仅让代码更具表达力,也往往比手动编写嵌套循环来处理复杂逻辑要高效和健壮得多。它鼓励我们以一种函数式编程的思维来处理数据流,将每个操作视为一个独立的、可组合的单元。
尽管
array_filter()
一个我经常看到的“陷阱”是关于
array_filter()
array_filter()
0
""
null
false
[]
$data = [0, 1, '', 'hello', false, null, [], [1, 2]]; $cleanedData = array_filter($data); print_r($cleanedData); // 输出: Array ( [1] => 1 [3] => hello [7] => Array ( [0] => 1 [1] => 2 ) )
但如果你希望保留
0
true
null
false
另一个需要留意的点是,
array_filter()
array_filter()
array_walk()
在性能方面,对于大多数PHP应用而言,
array_filter()
在这种极端情况下,一些优化策略可以考虑:
array_filter()
yield
array_filter()
microtime(true)
在我看来,在选择过滤方法时,代码的可读性、可维护性往往比微小的性能差异更重要。
array_filter()
以上就是如何在PHP中对数组进行条件过滤?array_filter()的高级用法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号