【发布时间】:2015-07-06 02:38:20
【问题描述】:
我在一个网站上工作,我试图让首页跳过显示缺货的产品。
商品展示代码如下:
$data = array(
'sort' => 'p.date_added',
'order' => 'DESC',
'start' => 0,
'limit' => $setting['limit']
);
$results = $this->model_catalog_product->getProducts($data);
foreach ($results as $result) {
if ($result['quantity'] <= 0) { continue; }
if ($result['image']) {
$image = $this->model_tool_image->resize($result['image'], $setting['image_width'], $setting['image_height']);
} else {
$image = false;
}
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
} else {
$price = false;
}
if ((float)$result['special']) {
$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
} else {
$special = false;
}
if ($this->config->get('config_review_status')) {
$rating = $result['rating'];
} else {
$rating = false;
}
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'price' => $price,
'special' => $special,
'rating' => $rating,
'reviews' => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
'href' => $this->url->link('product/product', 'product_id=' . $result['product_id']),
);
}
对于这个 foreach 循环,本例中的限制设置为 6,因此此代码运行 6 次以在首页显示 6 个项目。
为了跳过缺货商品,我添加了以下行:
if ($result['quantity'] <= 0) { continue; }
现在这段代码完成了它的工作,但是当它检测到一个库存为 0 的商品时,它会留下一个空白空间(因此它显示 5 个而不是显示 6 个产品空间)
当这段代码检测到库存为 0 的商品时,我想要完成的是增加 foreach 循环,使其运行 7 次而不是 6 次。
谢谢!
【问题讨论】:
-
最合乎逻辑的做法是在您的 MySQL 查询中添加
WHERE子句,特别是WHERE quantity > 0以便查询只会选择数量大于 0 的行。因为它看起来就像您为 MySQL 查询使用框架或库一样,我假设将诸如'where' => 'quantity > 0'之类的内容添加到$data将是解决方案,但我不知道框架,所以我不能确定。
标签: php arrays if-statement foreach opencart