php购物车,堆栈数量
我正在制作一个php购物车,您可以在其中添加产品,然后,产品的名称、数量和价格等订单详细信息将显示在页面底部以及订单总额。我想这样做,当你添加一个已经添加到购物车的产品时,它会堆叠数量。例如,如果您有一个像红杯这样的产品,价格为5美元,数量为1,然后您又将其添加到购物车中,数量为2,订单详细信息部分将显示红杯,数量为3,价格为15美元。我正在使用一个会话来存储购物车的产品及其详细信息 下面是创建会话的代码块,我知道我必须在else语句中编写一些内容,但我不知道如何访问购物车中元素的价格:php购物车,堆栈数量,php,Php,我正在制作一个php购物车,您可以在其中添加产品,然后,产品的名称、数量和价格等订单详细信息将显示在页面底部以及订单总额。我想这样做,当你添加一个已经添加到购物车的产品时,它会堆叠数量。例如,如果您有一个像红杯这样的产品,价格为5美元,数量为1,然后您又将其添加到购物车中,数量为2,订单详细信息部分将显示红杯,数量为3,价格为15美元。我正在使用一个会话来存储购物车的产品及其详细信息 下面是创建会话的代码块,我知道我必须在else语句中编写一些内容,但我不知道如何访问购物车中元素的价格: <
<?php
//session_unset();
//session_destroy();
if(isset($_POST["addtocart"])) {
//var_dump($_SESSION["cart"]);
$_SESSION["cos"] = array_values($_SESSION["cart"]);
if(isset($_SESSION["cart"])) {
$item_array_id=array_column($_SESSION["cart"],"id");
$item_array_cant=array_column($_SESSION["cart"],"cantitate");
if(!in_array($_POST["id"],$item_array_id)) {
$count=count($_SESSION["cart"]);
$item_array=array(
'id' => $_POST["id"],
'name' => $_POST["hidden_name"],
'price' => $_POST["hidden_price"],
'quantity' => $_POST["quantity"]
);
$_SESSION["cart"][$count]=$item_array;
}
**else**
{
}
} else {
$item_array=array(
'id' => $_POST["id"],
'name' => $_POST["hidden_name"],
'price' => $_POST["hidden_price"],
'quantity' => $_POST["quantity"]
);
$_SESSION["cart"][0]=$item_array;
}
}
if(isset($_GET['action'])){
if($_GET['action']=="delete"){
for($i=0;$i<count($_SESSION["cart"]);$i++) {
if($i==$_GET['id']) {
unset($_SESSION["cart"][$i]);
}
}
$_SESSION["cart"] = array_values($_SESSION["cart"]);
}
}
?>
如果您使用id作为购物车数组的键,那么找到一个重复项并将其添加到价格中将非常简单
<?php
if(isset($_POST["addtocart"])) {
if(isset($_SESSION["cart"])) {
$cart = $_SESSION['cart']; // just make addressing the cart easier
if(!isset($cart[$_POST['id']]) ) {
$cart[$_POST['id']] = ['id' => $_POST["id"],
'name' => $_POST["hidden_name"],
'price' => $_POST["hidden_price"],
'quantity' => $_POST["quantity"]
];
} else {
// get current quantity from cart and add new quantity
$q = $cart[$_POST['id']]['quantity'] + $_POST["quantity"];
$cart[$_POST['id']]['quantity'] = $q;
$cart[$_POST['id']]['price'] = $q * $_POST["hidden_price"];
}
} else {
$_SESSION['cart'][$_POST['id']] = ['id' => $_POST["id"],
'name' => $_POST["hidden_name"],
'price' => $_POST["hidden_price"],
'quantity' => $_POST["quantity"]
];
}
}
if(isset($\u SESSION[“cart”])测试其在此行中的存在性之前使用的Small Point
如果存在需要检查,您确实需要按逻辑顺序执行操作,那么良好的代码缩进将有助于我们阅读代码,更重要的是,它将帮助您调试代码,以实现您自己的利益。您可能会被要求在几周/几个月内修改此代码,最终您将感谢我。