我将购物车存储在PHP会话中,然后加载它以显示购物车中的项目。
问题是,目前,我看到的每个项目都没有合并,这意味着如果一个项目在购物车中添加了两次,它将显示两次。
如何按itemId合并结果?
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++)
{
$pid=$_SESSION['cart'][$i]['itemId'];
$q=$_SESSION['cart'][$i]['qty'];
if($q==0) continue;
$query2 = $con -> prepare("SELECT * FROM item_descr WHERE id_item = :idItem");
$query2-> bindValue (':idItem',$pid);
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_ASSOC);
?>
<div class="checkoutItems">
<span class='itemNameChck'><?php echo $row2['name']; ?> </a></span>
<span class="itemQtyChck"><?php echo $row2['price']; ?> </span>
<span class="itemQtyChck"><?php echo $q; ?> </span>
<span class="itemQtyChck"><?php $totalPerItem = $q * $row2['price']; echo $totalPerItem; ?> </span>
</div>
<?php
}
}
以下是我如何将商品添加到购物车中:
function addtocart($pid,$q)
{
if($pid<1 or $q<1) return;
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['itemId']=$pid;
$_SESSION['cart'][$max]['qty']=$q;
$max=count($_SESSION['cart']);
}
else
{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['itemId']=$pid;
$_SESSION['cart'][0]['qty']=$q;
$max=count($_SESSION['cart']);
}
//}
}
在我看来,您必须去掉包含购物车项目索引的ID。
// I mean this
// ||
// ||
// ' /
// '/
$_SESSION['cart'][$max]['qty']=$q;
只需将itemId
放在那里,在添加项之前,请检查是否设置了数组的此元素。
您编写了这段代码,每次都会向数组中添加新元素,现在您想要合并。这对我来说毫无意义。只有在必要的时候才添加新元素。否则,只更新数量。
在我看来,你的购物车应该是这样的:
$_SESSION['cart'][$itemid]['qty']=$q;
// example how to store other attributes
$_SESSION['cart'][$itemid]['name']="Rubber duck";
$_SESSION['cart'][$itemid]['color']="Yellow";
$_SESSION['cart'][$itemid]['size']="XXL";
$_SESSION['cart'][$itemid]['price']="1000";
然后,当添加项目时,您可以检查具有该项目ID的购物车项目是否包含任何元素。
if isarray($_SESSION['cart'][$itemid]) // when exists - add to previous quantity
$_SESSION['cart'][$itemid]['qty']= $_SESSION['cart'][$itemid]['qty'] + $q;
else // else - set quantity
$_SESSION['cart'][$itemid]['qty'] = $q;
这只是一个草稿/想法,但我希望它能对你有所帮助。
像这样的东西应该可以完成
function addtocart($pid,$q)
{
if($pid<1 or $q<1) return;
for($i=0;$i> count($_SESSION['cart']);$i++)
{
if($_SESSION['cart'][$i]["item_id"] == $pid)
{
$_SESSION['cart'][$i]['qty'] += $q
return;
}
}
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['itemId']=$pid;
$_SESSION['cart'][$max]['qty']=$q;
$max=count($_SESSION['cart']);
}
else
{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['itemId']=$pid;
$_SESSION['cart'][0]['qty']=$q;
$max=count($_SESSION['cart']);
}
}