我想从我的购物篮中计算我的$ _SESSION ['购物车'](单位)产品。
#check added stock
$units = (int) $_POST['units'];
$sizes_id = (int) $_POST['size_id'];
$in_stock = $db->GetScalar("SELECT p.units FROM products_sizes s
INNER JOIN products p ON p.product_id = s.product_id
WHERE s.id = '$sizes_id' LIMIT 1");
$total = isset($_SESSION['cart'][$sizes_id]) ? $_SESSION['cart'][$sizes_id]['units'] : 0;
$total += $units;
if($total <= $in_stock) {
if(isset($_SESSION['cart'][$sizes_id])) {
$_SESSION['cart'][$sizes_id]['units'] = $total;
} else {
$_SESSION['cart'][$sizes_id] = array('size' => $sizes_id, 'units' => $total);
}
$msg = 'Added';
$status = 1;
}else {
$msg = 'Product is not in the basket';
$status = 0;
}
这是输出的样子
Array(
[57] => Array
(
[size] => 57
[units] => 5
)
[56] => Array
(
[size] => 56
[units] => 1
)
)
答案 0 :(得分:1)
好的,
<?php
$total_units = 0;
foreach ($_SESSION['cart'] as $key => $value) {
$total_units += $value['units'];
}
echo $total_units;
&GT;
应该得到答案
答案 1 :(得分:1)
这应该做的工作:
$numUnits = 0;
foreach ($yourArray as $item)
$numUnits += $item['units'];