php筛选实现
PHP 数组筛选方法
使用 array_filter() 函数可以方便地筛选数组元素。该函数接受一个数组和一个回调函数,回调函数决定哪些元素保留。
$numbers = [1, 2, 3, 4, 5];
$filtered = array_filter($numbers, function($value) {
return $value % 2 == 0; // 筛选偶数
});
print_r($filtered); // 输出: Array ( [1] => 2 [3] => 4 )
自定义筛选条件
回调函数可以包含更复杂的逻辑,实现多条件筛选。
$users = [
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 20]
];
$filteredUsers = array_filter($users, function($user) {
return $user['age'] > 22 && $user['name'] != 'Bob';
});
print_r($filteredUsers);
保留键名或重置索引
array_filter() 默认保留原始键名,如需重置索引,可结合 array_values() 使用。
$filtered = array_filter($numbers, function($v) { return $v > 3; });
$reindexed = array_values($filtered);
print_r($reindexed); // 输出: Array ( [0] => 4 [1] => 5 )
使用箭头函数简化代码
PHP 7.4+ 支持箭头函数,使筛选代码更简洁。
$filtered = array_filter($numbers, fn($v) => $v > 2);
多维数组筛选
对多维数组筛选时,回调函数需处理子数组结构。
$products = [
['id' => 1, 'price' => 10],
['id' => 2, 'price' => 20],
['id' => 3, 'price' => 15]
];
$expensive = array_filter($products, fn($p) => $p['price'] > 12);
print_r($expensive);
筛选关联数组
针对关联数组,可通过键名和值组合条件筛选。
$data = ['a' => 1, 'b' => 2, 'c' => 3];
$result = array_filter($data, fn($v, $k) => $v > 1 && $k != 'b', ARRAY_FILTER_USE_BOTH);
print_r($result); // 输出: ['c' => 3]
性能优化建议
对于大型数组,考虑以下优化措施:

- 避免在回调函数中进行复杂计算
- 必要时先用
array_column()提取待筛选字段 - 对静态条件使用
array_reduce()可能更高效
$largeArray = [...]; // 假设是大数组
$column = array_column($largeArray, 'key_to_filter');
$filtered = array_filter($column, fn($v) => $v > $threshold);






