2011-09-22 89 views
2

我有這3個類:shopping cart - >orders - >products在購物車中添加產品的PHP中的問題

首先我添加一個產品,當我添加第二個產品時,我將與products中對象orders中的其他產品進行比較。 if count($product)==0,然後添加杉杉產品 如果count>0,我比較產品的id's新產品陣列中的我要補充:

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++; 
      } 

     } 
    } 

當我完成的比較,我一定要添加這些新產品,但這不起作用。我的錯誤是什麼?

+0

定義「不工作」的需要沒有檢查。你有錯誤嗎? – ceejayoz

回答

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子句之後),但如果沒有關於你認爲錯誤的解釋,很難說。

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元

相關問題