在商店购物车中添加产品的PHP问题

时间:2011-09-22 03:13:05

标签: php

我有以下3个课程:shopping cart - > orders - > products

首先我添加一个产品,当我添加第二个产品时,我会与对象products中数组orders中的其他产品进行比较。 if count($product)==0,然后添加第一个产品 if count>0,我将数组中产品的ID与我想要添加的新产品进行比较:

    public function setProduct($product,$new_quantity){
        if($this->num_product == 0) {
            $this->product[$this->num_product]=$product;
            $this->num_product++;
        } else if($this->num_product > 0) {
            for($i=0; $i < $this->num_product; $i++) {
                if($this->product[$i]->getIdproduct() == $product->getIdproduct()) {
                    $this->product[$i]->setQuantity($this->product[$i]->getquantity()+$new_quantity);
                    break;
                } else {
                    continue;
                }
                $this->product[$this->num_product]=$product;
                $this->num_product++;
            }

        }
    }

当我完成比较时,我必须添加这些新产品,但这不起作用。我的错是什么?

2 个答案:

答案 0 :(得分:1)

您的方法对于您想要做的事情来说非常复杂。

首先,$this->num_productcount($this->product)完全相同。那么为什么要使用变量来保存这些信息?

其次,无需将零产品和购物车中的某些产品分开,如果购物车中没有产品,for循环将无法执行。

我建议将此作为解决方案:

public function setProduct($product,$new_quantity){
   for($i=0; $i < count($this->product); $i++) {
        if($this->product[$i]->getIdproduct() == $product->getIdproduct()) {
            $this->product[$i]->setQuantity($this->product[$i]->getquantity() + $new_quantity);
            return; // we found our product, get out of the function.
        }
   }
   // the product was not found in the array, add it to the end
   $this->product[]=$product;
}

如果你想保留你的代码,我认为错误是你在循环的每次迭代中将产品添加到数组中(循环的最后两行,在if子句之后),但是如果没有一些关于你认为错误的解释,真的很难说。

答案 1 :(得分:0)

代码中的问题是for循环的最后两行永远不会被执行。如果if contidion为true,它将break循环,否则continue将无法到达这两行。最简单的方法是使用retun如果你的函数在循环后没有做任何事情。

 public function setProduct($product,$new_quantity){
        if($this->num_product == 0) {
            $this->product[$this->num_product]=$product;
            $this->num_product++;
        } else if($this->num_product > 0) {
            for($i=0; $i < $this->num_product; $i++) {
                if($this->product[$i]->getIdproduct() == $product->getIdproduct()) {
                    $this->product[$i]->setQuantity($this->product[$i]->getquantity()+$new_quantity);
                    return;
                }
            }
            $this->product[$this->num_product]=$product;
            $this->num_product++;
        }
    }

另见@krtek关于不检查0元素的需要

相关问题