我不知道如何通过再次添加来更新已经在购物篮中的产品数量。如果数量为 1,添加数量为 3 的相同产品后,应在购物篮中显示 4。我现在所能做的就是用新的数量替换添加的数量,或者在购物篮表中插入一个空元素,不包含任何产品详细信息。
<?php
// Products are added to the basket
if (!isset($_SESSION['basket'])) {
$_SESSION['basket'] = array();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['id'])) {
$_SESSION['basket'][$_POST['id']] = array(
'product_id'=>($_POST['id']),
'product_photo'=>($_POST['hidden_photo']),
'product_photo_alt'=>($_POST['hidden_photo_alt']),
'product_name'=>($_POST['hidden_name']),
'product_price'=>($_POST['hidden_price']),
'product_quantity'=>($_POST['quantity'])
);
}
}
// This is the code with which I can only insert an empty element in the basket table with no product details.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['id']) && isset($_POST['quantity'])) {
foreach ($_SESSION['basket'][$_POST['id']] as $item) {
if ($_item['product_id'] === $_SESSION['basket']['product_id']) {
$_SESSION['basket']['product_quantity'] += $item['product_quantity'];
}
}
}
}
// If I apply below code it just replaces the quantity:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['id']) && isset($_POST['quantity'])) {
foreach ($_SESSION['basket'] as $item) {
if ($_item['product_id'] === [$_POST['id']]) {
$item['product_quantity'] += $_POST['quantity'];
}
}
}
}
?>
茅侃侃