我将一个数组设置为$ _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"]);
}
答案 0 :(得分: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;
?>