2014-01-25 67 views
0

我正在學習PHP,並嘗試輸出「價格」列的總數。如何在foreach中獲取總數

下面是它看起來像現在: http://imgur.com/X00o4jS

下面的代碼:

  while($row = $result->fetch_array()){ 
      $rows[] = $row; 

     } 

     foreach($rows as $row){ 

      $food = $row["food"]; 
      $price = $row["price"]; 
      $id = $row['id']; 

      if(!empty($_POST[$id])){ 
      $qtyPrice = $price * $_POST[$id]; 
      $qty = $_POST[$id]; 

      } 

      echo "<tr> 
      <td>$food</td> 
      <td>$qty</td> 
      <td>$$qtyPrice</td> 
     </tr>"; 
     } 

回答

0

無需做2個循環。您正在使用1st while循環設置數組,然後使用第二個foreach循環來讀取它並顯示數據。

使用while循環直接生成html表格會更高效。您可以使用$total += $qtyPrice (same as $total = $total + $qtyPrice)。 只記得在循環之前將它設置爲0。

$total = 0; 

while($row = $result->fetch_array()){ 

     $food = $row["food"]; 
     $price = $row["price"]; 
     $id = $row['id']; 

     if(!empty($_POST[$id])){ 
     $qtyPrice = $price * $_POST[$id]; 
     $qty = $_POST[$id]; 

     $total += $qtyPrice; 

     echo "<tr> 
     <td>$food</td> 
     <td>$qty</td> 
     <td>$$qtyPrice</td> 
    </tr>"; 
    } 

//display the total in its separate row 
echo "<tr><td>Total:</td><td></td><td>$total</td></tr>"; 

希望這有助於!

+0

非常感謝!非常有用的信息! – jackdishman

0

設置一個變量開始循環,並在它加入qtyPrice之前。退出循環後打印該變量

$total = 0; 

foreach($rows as $row){ 

      $food = $row["food"]; 
      $price = $row["price"]; 
      $id = $row['id']; 

      if(!empty($_POST[$id])){ 
      $qtyPrice = $price * $_POST[$id]; 
      $total += $qtyPrice; 
      $qty = $_POST[$id]; 

      } 

      echo "<tr> 
      <td>$food</td> 
      <td>$qty</td> 
      <td>$$qtyPrice</td> 
     </tr>"; 
     } 
    echo $total;