【问题标题】:Increasing loop by 1 for a foreach data array将 foreach 数据数组的循环增加 1
【发布时间】: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 &gt; 0 以便查询只会选择数量大于 0 的行。因为它看起来就像您为 MySQL 查询使用框架或库一样,我假设将诸如 'where' =&gt; 'quantity &gt; 0' 之类的内容添加到 $data 将是解决方案,但我不知道框架,所以我不能确定。

标签: php arrays if-statement foreach opencart


【解决方案1】:

所以我相信我已经解决了这个问题,而不必乱搞 MySQL。

我刚刚添加了一个带有中断代码的计数器系统,谈谈基础知识。

基本上我已经将代码限制设置为外部变量 $x 设置为我的中断变量。

当缺货值进入计数器时,计数器减 1,而在存货项目中,计数器加 1。

因此,当计数器命中我的中断变量时,代码将关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2019-06-28
    • 1970-01-01
    • 2015-03-28
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多