PHP计算购物车

时间:2015-11-03 14:15:35

标签: php arrays session

$_SESSION['products']保存了多个购物车项目,我希望总数量显示在标题上

我尝试使用以下脚本获取总数量:

  if(isset($_SESSION['products'])) {

      $totalQty = 0;

      foreach($_SESSION['products'] as $itemQty){
          $totalQty += $itemQty;
      }

  }

  echo $totalquantity;

print_r($_SESSION['products'])获取下方购物车中的当前商品:

Array
(
    [0] => Array
    (
         [p_id] => 31 
         [p_name] => Product 31
         [p_price] => 28.80
         [p_qty] => 2
    )

    [1] => Array
    (
         [p_id] => 46 
         [p_name] => Product 46
         [p_price] => 18.00
         [p_qty] => 3
    )

    [2] => Array
    (
         [p_id] => 12 
         [p_name] => Product 12
         [p_price] => 63.00
         [p_qty] => 1
    )
)

如何循环遍历$ _SESSION并动态获取数组中的[p_qty]总数?

2 个答案:

答案 0 :(得分:2)

只需将array_column()array_sum()

一起使用即可
{"serverTemplates": [
    {
        "sequence": "1",
        "templateId": "'.$template_id.'"
     }
    ],
   "inlineTemplates": [
    {
      "sequence": "2",
       "recipients": {
            "signers": [
                   {
                     "email": "'.$emp_rec['email_id'].'",
                     "name": "'.$emp_rec['name'].'",
                     "recipientId": "1",
                     "roleName": "Employee",
                     "routingOrder": "1"
                   }
                 ]
       }
     }
  ]
}

Demo

答案 1 :(得分:1)

尝试使用此方法-在Codeigniter中计算总量

<?php 
foreach($this->cart->contents() as $itemQty){
$totalQty+=$itemQty['qty'];
}
?>
<?php echo $totalQty;?>