2011-05-09 137 views
2

我試圖創建一個PHP函數,添加一個項目到購物車。我想要它做的是檢查數組,看看該項目是否已經在那裏,如果是增加數量,如果不是在購物車中創建項目。PHP添加到購物車的問題

它是在做什麼而不是它添加一個項目,它會第一次工作(如果項目已經存在,它只會增加數量),但如果添加另一個項目,它會一直創建新的實例在購物車 如項目

項目1 - 數量4 項目2 - 數量1個 項目2 - 數量1個 項目2 - 數量1 ...等等...

下面

是我到目前爲止的代碼?

function add_item ($id, $qty) 
    { 
     $count=$this->countItems; 
     echo "uytfdgghjkl;kj<br>"; 
     $added = false; 
     if($count>0) 
     { 
      $i=0; 
      while($added == false) 
      { 
       echo "fghjkl<br>"; 
       $tid = $this->items[$i]->getId(); 
       echo "new ID: ".$tid."<br>"; 
       echo "old ID: ".$id."<br>"; 
       echo $i; 
       if($tid == $id) 
       { 
        $amount = $this->items[$i]->getQty(); 
        $this->items[$i]->setQty($amount+1); 
        $added = true; 
        //$i++; 
        //break; 
       } 
       if($added == true) 
       { 
        break; 
       } 
       else //if($added == false) 
       { 
        $this->items[$this->countItems] = new OrderItem($id, $qty); 
        //$this->total = $total+ ($qty *$price); 
        $this->countItems++; 
        $added = true; 
        //break; 
       } 
       //else break; 
       $i++; 
      } 

     } 
     else 
     { 
      $this->items[$this->countItems] = new OrderItem($id, $qty); 
      //$this->total = $total+ ($qty *$price); 
      $this->countItems++; 
     } 
    } 
+0

這段代碼有很多錯誤。但對於初學者,你不應該檢查重複項 - 如果使用SKU作爲索引鍵不是不言而喻的話,那麼你需要花更多的時間來學習和運用算法。 – symcbean 2011-05-09 16:29:14

回答

0

問題是,您並未先搜索整個數組,以查看該項是否存在。下面的代碼應該可以工作,但我可能犯了一個錯字或別的東西,所以請確保你仔細檢查它。

function add_item ($id, $qty) 
    { 
     $count=$this->countItems; 
     echo "uytfdgghjkl;kj<br>"; 
     $added = false; 
     if($count>0) 
     { 
      for($i=0; $i < $count; $i++) 
      { 
       echo "fghjkl<br>"; 
       $tid = $this->items[$i]->getId(); 
       echo "new ID: ".$tid."<br>"; 
       echo "old ID: ".$id."<br>"; 
       echo $i; 
       if($tid == $id) 
       { 
        $amount = $this->items[$i]->getQty(); 
        $this->items[$i]->setQty($amount+1); 
        $added = true; 
        break; 
       } 
      } 

     } 
     if(!$added) 
     { 
      $this->items[$this->countItems] = new OrderItem($id, $qty); 
      //$this->total = $total+ ($qty *$price); 
      $this->countItems++; 
     } 
    } 

一個更好的辦法是使用字典

即。

$arr = array(); 
$arr['item_id'] = new OrderItem(...); 

然後你可以檢查的項目是使用數組:

if(isset($arr[$id])){ 
    ... 
} 
0

的邏輯是有缺陷的。只有碰巧是購物車中的第一件商品,代碼纔會增加商品的數量。否則,它會添加該項目。在這裏證明:不是

if($added == true) // if this cart item's quantity was incremented 
{ 
    break; 
} 
else // add item 
{ 
    $this->items[$this->countItems] = new OrderItem($id, $qty); 
    // etc... 
} 

,您應該刪除從環路new OrderItem($id, $qty)並通過所有的車項目後,循環檢查$added值。爲此,您需要使用$count通過for(而不是一段時間)進行循環。