php - 处理两次将相同的商品添加到购物车
问题描述
我正在制作一个电子商务网络应用程序,并且我正在尝试编写代码来处理如果用户单击已经在购物篮中的项目上的添加到购物篮按钮但它似乎无法正常工作。如果第二次单击该按钮,则第一个项目数量将被第二个项目覆盖
if ($action === 'add_product') {
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : null;
$price = isset($_REQUEST['price']) ? (float) $_REQUEST['price'] : null;
$quantity = isset($_REQUEST['quantity']) ? (int) $_REQUEST['quantity'] : null;
$name = isset($_REQUEST['name']) ? trim($_REQUEST['name']) : null;
if ($id && $price && $quantity) {
$_SESSION['cart'][$id] = [
'id' => $id,
'price' => $price,
'quantity' => $quantity,
'name' => $name
];
} // if the action is increment, increse the quantity of the item.
} elseif ($action === 'increment' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] += 1;
//if the action is decrement, decrease the quantity of item by 1
} elseif(array_key_exists('id',$_SESSION['cart'][$_REQUEST['id']))//here is where it is supposed to handle adding the same item twice {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] += 1;
} elseif ($action === 'decrement' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] -= 1;
if ($_SESSION['cart'][$_REQUEST['id']]['quantity'] <= 0) {
unset($_SESSION['cart'][$_REQUEST['id']]);
}
} elseif ($action === 'remove' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
unset($_SESSION['cart'][$_REQUEST['id']]);
}
我已经评论了应该添加到数量的位置,但它没有添加到数量并更新它只是覆盖了旧的质量,我不知道为什么。我也尝试过if(in_array($id,$_SESSION['cart'][$_REQUEST['id']))
,但这也没有用。我不太明白为什么它不起作用,所以非常感谢任何帮助。