PHP会话总和购物车数量甚至不同的产品ID

时间:2018-04-12 07:04:47

标签: php loops session

我有$getProductID = mysqli_real_escape_string($con, $_POST['productID']); $getQuantity = mysqli_real_escape_string($con, $_POST['quantity']); foreach($_POST as $key => $value) { $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); } $qProduct = mysqli_query($con, "SELECT * FROM tb_product WHERE productid = '" . $getProductID . "'"); $dProduct = mysqli_fetch_array($qProduct); $product_id = $dProduct['productid']; $product_name = $dProduct['product_name']; $product_price = $dProduct['product_price']; $new_product["productid"] = $product_id; $new_product["product_name"] = $product_name; $new_product["product_price"] = $product_price; $new_product["quantity"] = $getQuantity; if(isset($_SESSION["products"])) { if(isset($_SESSION["products"][$new_product['productid']])) { unset($_SESSION["products"][$new_product['productid']]); } } $_SESSION["products"][$new_product['productid']] = $new_product; $total_items = count($_SESSION["products"]); foreach($_SESSION["products"] as $product) { $product_quantity = $product["quantity"]; } die(json_encode(array('items'=>$product_quantity))); 添加产品购物车。

session

然后我想获得产品数量的foreach($_SESSION["products"] as $product) { echo $product_quantity = $product["quantity"]; }

{{1}}

我也可以获得数量,直到我尝试添加另一个产品购物车时,它不会对数量求和。

示例,在Product1上我添加到购物车5pcs(我可以看到数量是5)
然后我将Product2添加到购物车3pc(它显示53应该是8)。

我的问题,即使产品ID的数量总和如何相加?

2 个答案:

答案 0 :(得分:2)

如下所示更改循环,在循环内部求和并在循环外移动回声。

$product_quantity = 0;
foreach($_SESSION["products"] as $product)
{
    $product_quantity += $product["quantity"];
}
echo $product_quantity;

答案 1 :(得分:1)

我认为因为你的编码有问题

//Incorrect

 foreach($_SESSION["products"] as $product)
 {
        echo $product_quantity = $product["quantity"];
 }
 //first loop echo-ed 5
 //second loop echo-ed 3
 //so it show 53

//Correct
$product_quantity = 0;

foreach($_SESSION["products"] as $product)
{
   $product_quantity += $product["quantity"];
}

echo $product_quantity;