php筛选实现
PHP 数组筛选方法
在 PHP 中,可以使用多种方法对数组进行筛选操作,以下是几种常见的实现方式:
array_filter 函数
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 === 0;
});
自定义筛选条件

$users = [
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 20]
];
$adults = array_filter($users, function($user) {
return $user['age'] >= 25;
});
使用 array_reduce 筛选
$products = [
['name' => 'Laptop', 'price' => 999],
['name' => 'Phone', 'price' => 599],
['name' => 'Tablet', 'price' => 299]
];
$expensiveProducts = array_reduce($products, function($carry, $item) {
if ($item['price'] > 500) {
$carry[] = $item;
}
return $carry;
}, []);
数据库查询筛选
使用 WHERE 条件

$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > :age");
$stmt->execute([':age' => 25]);
$adults = $stmt->fetchAll(PDO::FETCH_ASSOC);
动态构建查询条件
$filters = [
'status' => 'active',
'role' => 'admin'
];
$where = [];
$params = [];
foreach ($filters as $field => $value) {
$where[] = "$field = :$field";
$params[":$field"] = $value;
}
$sql = "SELECT * FROM users";
if (!empty($where)) {
$sql .= " WHERE " . implode(' AND ', $where);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$filteredUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
高级筛选技巧
多条件筛选
$criteria = [
'min_price' => 100,
'max_price' => 1000,
'category' => 'electronics'
];
$products = array_filter($allProducts, function($product) use ($criteria) {
return $product['price'] >= $criteria['min_price']
&& $product['price'] <= $criteria['max_price']
&& $product['category'] === $criteria['category'];
});
链式筛选方法
class Filter {
private $data;
public function __construct(array $data) {
$this->data = $data;
}
public function where($key, $value) {
$this->data = array_filter($this->data, function($item) use ($key, $value) {
return $item[$key] == $value;
});
return $this;
}
public function get() {
return $this->data;
}
}
$filtered = (new Filter($users))
->where('age', 25)
->where('status', 'active')
->get();
以上方法可以根据具体需求选择使用,数组筛选适用于内存中的数据操作,而数据库查询筛选则更适合处理大量数据。






