[英]Php add to shopping cart problem
我試圖創建一個將商品添加到購物車的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++;
}
}
問題在於您不是先搜索整個數組以查看其中是否存在該項。 下面的代碼應該可以工作,但是我可能輸入了錯字或其他錯誤,因此請確保仔細檢查。
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])){
...
}
邏輯有缺陷。 僅當碰巧是購物車中的第一件物品時,該代碼才會增加該物品的數量。 否則,它將添加該項目。 在這里證明:
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
通過所有的車項目后循環。 對於這個工作,你需要通過循環for
使用(而不是同時) $count
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.