[英]Echo cart with the number of quantity of items that are added to cart
我一直在关注ecom网络教程,并且已经多次更改了代码,但仍然没有正确执行。问题是根据产品数量而不是产品ID来更改购物车旁边回显的编号。
Shop.php代码:
<a href="#tab2">CART <span class="badge">
<?php
if(isset($_SESSION["shopping_cart"])) {
echo count($_SESSION["shopping_cart"]);
} else {
echo '0';}
?>
</span></a>
action.php代码:
<?php
if (isset($_POST["product_id"])) {
$order_table = '';
$message = '';
if ($_POST["action"] == "add") {
if (isset($_SESSION["shopping_cart"])) {
$is_available = 0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
if ($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"]) {
$is_available++;
$_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];
}
}
if ($is_available < 1) {
$item_array = array(
'product_id' => $_POST["product_id"],
'product_name' => $_POST["product_name"],
'product_price' => $_POST["product_price"],
'product_quantity' => $_POST["product_quantity"]
);
$_SESSION["shopping_cart"][] = $item_array;
}
} else {
$item_array = array(
'product_id' => $_POST["product_id"],
'product_name' => $_POST["product_name"],
'product_price' => $_POST["product_price"],
'product_quantity' => $_POST["product_quantity"]
);
$_SESSION["shopping_cart"][] = $item_array;
}
}
}
?>
您要使用循环存储购物车中每个项目的数量:
function getCartQty()
{
# If there is nothing in the cart, return 0
if(empty($_SESSION['shopping_cart']))
return 0;
# Store array
$qty = array();
# Loop items in cart
foreach($_SESSION["shopping_cart"] as $item){
# Store the quantity of each item
$qty[] = $item['product_quantity'];
}
# Return the sum
return array_sum($qty);
}
?>
<a href="#tab2">CART <span class="badge"><?php echo getCartQty() ?></span></a>
count()
将返回数组中元素的数量。 在$ _SESSION数组中存储的购物车数组上运行时,您要计算的是唯一商品的数量。
由于每种产品都有数量值,因此您需要检索这些数量的总和。 您可以使用以下函数来执行该计算:
function my_shopping_cart_total_product_count() {
$product_count = 0;
if ( isset( $_SESSION['shopping_cart'] ) ) {
$product_count = array_sum( array_column( $_SESSION['shopping_cart'], 'product_quantity' ) );
}
return $product_count;
}
在上面的示例中,我使用array_column
获取包含所有产品数量的数组。 然后,我通过array_sum
运行它以获取总数。 您当然可以简单地使用foreach循环。
用法:
<a href="#tab2">CART <span class="badge"><?php echo my_shopping_cart_total_product_count(); ?></span></a>
说明文件:
补充笔记:
action.php中的代码非常令人担忧。 似乎缺乏用户输入清理功能。 我建议研究数据清理以提高安全性。
您可以在Magento后端中更改设置,以获取商品的总数量,而不是不同产品的数量:
这适用于默认的Magento主题,因此您可以使其适合您自己的主题。
您也可以尝试以下操作:
# return shopping cart items count means how many sku add to shopping cart
Mage::helper('checkout/cart')->getItemCount()
# return shopping cart items summary (suppose you add sku1 6 qty and sku2 3 qty = total 9 qty return)
Mage::helper('checkout/cart')->getSummaryCount()
资料来源: https : //magento.stackexchange.com/a/23496/46249
注意:不要在Magento中使用$_SESSION
,有其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.