我为我的公司电子商务解决方案创建了一个方面菜单。您可以看到此here的演示。整个过程是几百行代码分布在4个文件中,所以我不会在这里包含所有内容,但会粘贴任何相关的代码。
代码的基本流程是:
我针对数据库运行单个查询以获取活动构面的有效产品的完整列表,然后对原始产品列表使用简单的in_array检查。这是目前正在使用的实际代码:
if(!empty($this->filters)) {
//Get a list of product IDs that match the active facets
$query = "SELECT p.pId
FROM products p
LEFT JOIN filterproducts fp
ON p.pId = fp.fpProductId
WHERE p.pDisplay <> 0
AND ( ";
$or = "";
foreach($this->filters as $constraint => $facets) {
$query .= $or . "(";
$subOr = "";
foreach($facets as $facet => $set) {
if($set) {
$query .= $subOr . "fp.fpFacetId = " . (int)$facet;
$subOr = " OR ";
}
}
$query .= ")";
$or = " OR ";
}
$query .= ")
GROUP BY p.pId
HAVING COUNT(p.pId) = " . count($this->filters);
$results = $this->dbConn->query($query);
if($this->dbConn->errno) {
trigger_error('An error occured whilst loading products matching active facets.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->dbConn->errno . ']: ' . $this->dbConn->error, E_USER_WARNING);
} elseif($results->num_rows) {
while($row = $results->fetch_assoc()) {
$this->validProds[] = $row['pId'];
}
$results->free();
}
//Compare products with the list of valid IDs and unset any invalid products.
foreach($this->products as $product) {
if(!in_array($product->id, $this->validProds)) {
unset($this->products[$product->id]);
}
}
}
这是方面菜单工作的唯一方法吗?我想不出任何其他方式,但肯定有更有效的方法来实现这一目标。我非常感谢能够提出更好的创建方面菜单的人。