2011-09-22 2 views
2

저는 shopping cart ->orders ->products의 3 가지 클래스가 있습니다.php에서 쇼핑 카트에 상품을 넣는 데 문제가 있습니다.

먼저 두 번째 제품을 추가 할 때 orders 개체의 배열 products에있는 다른 제품과 비교합니다. 내가 비교를 완료하면

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

     } 
    } 

, 나는 다음을 추가해야합니다 : if count($product)==0 다음, 전나무 제품 경우 count>0을 추가, 내가 추가 할 새로운 제품과 함께 배열의 제품의 id's 비교 새 제품이지만 작동하지 않습니다. 내 실수는 무엇입니까?

+0

는 "작동하지 않는"정의 0 요소에 대한 어떤 검사의 필요성에 대해 말씀. 오류가 있습니까? – ceejayoz

답변

1

당신의 방법은 당신이하고 싶은 일에 정말로 복잡합니다.

우선 $this->num_product은 정확히 count($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

관련 문제