php实现筛选查询
使用数组函数筛选查询
在PHP中,可以利用数组函数如array_filter()进行数据筛选。该方法适用于内存中的数组数据。
$data = [
['id' => 1, 'name' => 'Apple', 'price' => 2.5],
['id' => 2, 'name' => 'Banana', 'price' => 1.2],
['id' => 3, 'name' => 'Orange', 'price' => 3.0]
];
$filtered = array_filter($data, function($item) {
return $item['price'] < 3.0;
});
数据库查询筛选
当需要从数据库筛选数据时,应使用SQL的WHERE子句配合预处理语句防止SQL注入。
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$stmt = $pdo->prepare("SELECT * FROM products WHERE price < :price");
$stmt->execute(['price' => 3.0]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
多条件筛选实现
对于需要多个筛选条件的场景,可以动态构建SQL查询。

$conditions = [];
$params = [];
if (isset($_GET['min_price'])) {
$conditions[] = "price >= :min_price";
$params['min_price'] = $_GET['min_price'];
}
if (isset($_GET['category'])) {
$conditions[] = "category_id = :category";
$params['category'] = $_GET['category'];
}
$sql = "SELECT * FROM products";
if (!empty($conditions)) {
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
使用ORM进行筛选
现代PHP框架通常提供ORM工具简化筛选操作。以Laravel的Eloquent为例:
$query = Product::query();
if ($request->has('min_price')) {
$query->where('price', '>=', $request->input('min_price'));
}
if ($request->has('category')) {
$query->where('category_id', $request->input('category'));
}
$products = $query->get();
前端筛选与AJAX结合
实现实时筛选可结合前端JavaScript和AJAX请求:

// 前端代码
document.getElementById('filter-form').addEventListener('change', function() {
fetch('/api/products?' + new URLSearchParams(new FormData(this)))
.then(response => response.json())
.then(data => updateResults(data));
});
// 后端API处理
$app->get('/api/products', function(Request $request) {
$query = Product::query();
if ($request->has('search')) {
$query->where('name', 'like', '%'.$request->input('search').'%');
}
return $query->paginate(10);
});
性能优化建议
对于大型数据集,应确保数据库表有适当的索引。在筛选字段上创建索引可显著提高查询速度:
CREATE INDEX idx_price ON products(price);
CREATE INDEX idx_category ON products(category_id);
分页处理避免返回过多数据:
$perPage = 10;
$page = $_GET['page'] ?? 1;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare("SELECT * FROM products LIMIT :offset, :perPage");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();






