我使用php实现了简单的购物车。我可以在购物车中添加product,它会添加到数组中。我得到我的产品id在url上,当我点击添加到购物车按钮基于该url id我从数据库中获取产品数据,并添加到会话数组,但我的问题是,当我添加相同的产品,我在会话中获得新的条目,而不是更新该产品的数量。那么我写什么代码来更新购物车数量,如果product_id已经存在。
这是使用$_SESSION['cart']
的print_r数组值。
[cart] => Array
(
[0] => Array
(
[product-id] => 1
[item] => mango
[unitprice] => 20
[quantity] => 1
)
[1] => Array
(
[product-id] =>2
[item] => chickoo
[unitprice] => 20
[quantity] => 1
)
)
听起来您需要确保product_id
尚未在会话数组中。试试下面的
$found = false;
foreach($_SESSION['cart'] as $product)
{
if($_REQUEST['product_id'] == $product['product_id']) {
$found = true;
break;
}
}
if($found)
{
$_SESSION['cart'][$_REQUEST['product_id']]['quantity'] += 1;
} else {
// go get new product and add to $_SESSION['cart']
}