2014-10-27 87 views
1

我正在製作購物車系統,並且我的會話正在使用foreach()函數顯示。在這個函數裏面,我有一個名爲$ item_price的變量。我希望將所有$ item_price加起來,這樣我就可以得到總計。PHP將所有的值加起來foreach()

這怎麼辦?我不知道這個問題應該如何解決:/

這是我的foreach()代碼:

foreach($session_cart as $cart_items) { 

    $fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'"); 
    while($shop_items = mysql_fetch_array($fetch_info)) { 
    $item_id = $shop_items['item_id']; 
    $item_name = $shop_items['item_name']; 
    $item_quantity = count(array_keys($session_quantity, $item_id)); 
    $item_price = $shop_items['item_price'] * $item_quantity; } 

    $cartOutput .= '<h2>'.$item_name.'</h2>'; 
    $cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>'; 
    $cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>'; 
    $cartOutput .= '<a> ID: '.$item_id.'</a><br><br>'; 

    } 
+0

發佈您的代碼,使我們可以幫助適當。 – 2014-10-27 19:01:22

+0

它是一個不可見的'foreach()'函數嗎? – 2014-10-27 19:02:21

+0

如果通過「變量名爲$ item_price」,你實際上是指數組鍵和值,那麼['array_column'](http://php.net/array_column)+ ['array_sum'](http://php.net/ array_sum)就足夠了。 – mario 2014-10-27 19:02:35

回答

0

使用更新的代碼:

$total = 0; 
    foreach($session_cart as $cart_items) { 

     $fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'"); 
     // while($shop_items = mysql_fetch_array($fetch_info)) { //<- No need of loop here as only one will be returned everytime 
     $shop_items = mysql_fetch_assoc($fetch_info); //<- use this instead 
     $item_id = $shop_items['item_id']; 
     $item_name = $shop_items['item_name']; 
     $item_quantity = count(array_keys($session_quantity, $item_id)); 
     $item_price = $shop_items['item_price'] * $item_quantity; 
     //} //<- Closing while loop removed 

     $cartOutput .= '<h2>'.$item_name.'</h2>'; 
     $cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>'; 
     $cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>'; 
     $cartOutput .= '<a> ID: '.$item_id.'</a><br><br>'; 

     $total+=$item_price; //<- Sums up for grand total 
     } 

     echo $total; //<- shows grand total 
+0

非常感謝你 - 它完全按照我的需要工作! :d – FrossBlock 2014-10-27 19:27:40

0
$total = 0; 
foreach($array as $row) 
{ 
    $total += $row['item_price']; 
    //the rest of your code in foreach 
} 
echo $total; 
+0

我需要它在foreach之外() – FrossBlock 2014-10-27 19:13:37