2014-10-27 71 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