以下功能位于购物车页面上,在用户从以前的产品页面添加产品后。问题是我需要多维数组来更新购物车中的数量以添加相同的产品代码。
有人可以帮我添加一个if语句,以便在添加相同的产品代码时数量增加吗?
喜欢这个答案,但是我的添加到购物车是不同的。PHP 会话购物车:如果产品已经是会话 ID 则更新产品
function AddToCart()
{
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : '';
$itemcount = isset($_SESSION
['itemcount']) ? $_SESSION['itemcount'] : 0;
{
$i = array_search($_POST['productcode'], $cart[PRODUCTCODE]);
$cart[PRODUCTCODE] [$itemcount] = $_POST['productcode'];
$cart[PRODUCTNAME] [$itemcount] = $_POST['productname'];
$cart[QUANTITY][$itemcount] = intval($_POST['quantity']);
$cart[PRICE][$itemcount] = $_POST['price'];
$itemcount = $itemcount + 1;
if(strlen($error) == 0) {
$_SESSION['cart'] = $cart;
$_SESSION['itemcount'] = $itemcount;
}
return $error;
}
试试这个。
//check for an existing match
$found = FALSE;
if($cart){
$idx = 0;
foreach($cart[PRODUCTCODE] as $idx => $product){
if($product == $_POST['productcode']){
$found = TRUE;
break;
}
}
}
//if we found a match
if($found){
$cart[QUANTITY][$idx] += intval($_POST['quantity']);
}
//otherwise add new item
else{
//your other code here
}