【发布时间】:2019-05-05 17:45:28
【问题描述】:
我正在尝试开发一个存在于会话中的购物车,购物车不能有任何重复项,因此需要添加的每个项目都是唯一的,否则它只会警告用户它已被添加。
我通过合并一个数组和一个 if 语句来检查它是否已经存在于该变量中,逻辑似乎仍然允许重复并由于某种原因在某个点停止。
//We search for the product that has been clicked on
$sql = $conn->prepare('SELECT * FROM product WHERE product_id= :product_id');
$sql -> execute(['product_id' => $product_id]); //execute the statement
$row = $sql->fetch();
$product_name = $row['product_name'];
$product_id = $row['product_id'];
$product_price = $row['product_price'];
//You could perform another search here to obtain the product image
$cartArray = array(
$product_id=>array(
'product_name'=>$product_name,
'product_id'=>$product_id,
'product_price'=>$product_price,
'product_quantity'=>1
)
);
// we perform some logic that detects if the product is already in the basket.
// If it is, we display an error message. Increasing quantity is handled on the cart page
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
$status = "<div class='box'>Product is added to your cart!</div>";
}else{
$array_keys = array_keys($_SESSION["shopping_cart"]);
if(in_array($product_id,$array_keys)) {
$status = "<div class='box' style='color:red;'>
Product is already added to your cart!</div>";
} else {
$_SESSION["shopping_cart"] = array_merge(
$_SESSION["shopping_cart"],
$cartArray
);
$status = "<div class='box'>Product is added to your cart!</div>";
}
}
}
I would like to know if there was anything that I need to do differently to prevent duplication
【问题讨论】:
-
您的逻辑似乎有效,但可以缩短和简化。你能分享一下允许复制的案例吗?你遇到过吗?