PHP在比较时获取数组值的总和

时间:2013-12-14 22:50:33

标签: php arrays

我有一系列信息状态和总计。我想知道如何获得每个州的所有总计的总和。

我知道我必须使用循环,但我不确定哪个 - 我该怎么做?

这是我到目前为止所拥有的。它从数据库中制作数组。

$WorkFind = mysql_query(
  "SELECT Customers.State, WorkOrders.Total 
   FROM WorkOrders 
   INNER JOIN Customers 
   ON WorkOrders.CID=Customers.ID 
   WHERE WorkOrders.Type <> 'Warranty' 
   AND (WorkOrders.Status <> 'Closed' 
   OR WorkOrders.Status <> 'Cancelled') 
   AND WorkOrders.TransferID='0' 
   ORDER BY Customers.State ASC");

while ($Work = mysql_fetch_array($WorkFind)) { 
}

while循环创建了数组,但我不确定要放入什么。

我使用的是PHP 5.3和MYSQL 5.2

1 个答案:

答案 0 :(得分:1)

试试这个:

$WorkFind = mysql_query("SELECT Customers.State AS State, WorkOrders.Total AS Total -- ...");

$total = array();

while ($Work = mysql_fetch_array($WorkFind)) {
  $state = $Work['State'];

  if (!isset($total[$state])) {
    $total[$state] = 0;
  }

  $total[$state] += $Work['Total'];
}

// format as simple table

echo '<table><tr><th>State</th><th>Total</th></tr>';

foreach ($total as $state_name => $state_total) {
  echo '<tr><td>' . $state_name . '</td><td>' . $state_total . '</td></tr>';
}

echo '</table>';