2015-11-03 41 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