0

我在 $_SESSION["cart_array"] 中设置了一个数组,当商品在购物车中时,输出就是这样。

Array ( [0] => Array ( [item_id] => 1 [quantity] => 6 ) [1] => Array ( [item_id] => 2 [quantity] => 1 ) )

我正在尝试创建一个 foreach 循环来遍历并计算“数量”值以获得购物车项目的总计数,到目前为止我有以下内容,但我只是不知道如何将其放入字符串变量中,所以我可以在其他页面上显示。

    $cartCount = array();
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartCount = 0;
} else {
    foreach ($_SESSION["cart_array"] as $each_item) {
        //$cartCount += $each_item['quantity']; <-- commented out as not working.
        //$cartCount[$each_item['item_id']] += $each_item['quantity']; <-- commented out as not working.
    }
    //Print array for debugging purposes
    print_r($_SESSION["cart_array"]);
}  
4

1 回答 1

1

这必须工作:

<?php

session_start();

$cartCount = 0;
if(isset($_SESSION['cart_array']) AND is_array(@$_SESSION['cart_array'])){
    foreach($_SESSION['cart_array'] AS $each_item){
        $cartCount = $cartCount + $each_item['quantity'];
    }
}

echo $cartCount;

?>
于 2012-09-18T05:38:57.053 回答