PHP将foreach()中的所有值相加

时间:2014-10-27 18:59:10

标签: php function foreach shopping-cart

我正在制作购物车系统,我的会话正在使用foreach()函数显示。在这个函数中,我有一个名为$ item_price的变量。我希望所有$ item_price都加起来,以便我最终获得总计。

怎么可以这样做?我不知道应该如何解决这个问题:/

这是我的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>';

  }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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