2015-11-03 33 views
0

$_SESSION['products']到保存多个购物车的物品,我想必须要对报头显示PHP数总量在车

我试图让总量与下​​面的脚本总量:

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

只要使用array_column()array_sum()

echo array_sum(array_column($_SESSION['products'], 'p_qty')); 

Demo

+0

感谢,作品真棒!对于那些使用PHP <5.5的人可以使用库 - > https://github.com/ramsey/array_column – conmen