5

这里有人可以帮我解决这个问题吗?我只想获取某列的总数或总和,请参考下图。已经尝试对此进行排序 2 天,但没有运气,希望有人可以帮助我。我非常感谢,并提前感谢。

这是一个示例图片http://www.freeimagehosting.net/pig81

<?php $sql = "SELECT name, doc_date, descs, debit, credit FROM statement WHERE  
member_id = $member_id ORDER BY doc_date";

$query = mysql_query($sql);
$combinedResults = array();

while($result = mysql_fetch_array($query)) {
$combinedResults[$result[`name`]][] = array(`name` => $result[`name`], `doc_date` =>   
$result[`doc_date`], `descs` => $result[`descs`],`debit` => $result[`debit`], `credit` 
=> $result[`credit`]);}

foreach(array_keys($combinedResults) as $groupKey) { ?>
<table>
  <tr><?php  foreach($combinedResults[$groupKey] as $item) {?>
    <td>Date</td>
    <td>Description</td>
    <td>Debit</td>
    <td>Credit</td>
    <td>Balance</td>
  </tr>
<tr>
<td colspan="2"><?php  echo $groupKey; ?></td>
<td width="105">&nbsp;</td>
<td width="105">&nbsp;</td>
<td width="105">&nbsp;</td>
</tr>
<tr><?php  foreach($combinedResults[$groupKey] as $item) {?>
<td><?php echo $item[`doc_date`];?></td>
<td><?php echo $item[`descs`];?></td>
<td><?php echo $item[`debit`];?></td>
<td><?php echo $item[`credit`]; ?></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>sum of debit goes here</td>
</tr>
<?php }} ?>
</table>
4

2 回答 2

2

你可以用类似的东西改变你的 SQL 语句

SELECT name, doc_date, descs, debit, credit, SUM(debit) AS sum FROM statement WHERE member_id = $member_id ORDER BY doc_date

然后你打印它

<?php echo $item['sum']; ?>

您可能还想看看PDO和替换函数的准备好的语句。mysql_

于 2012-04-25T17:26:03.937 回答
1

我已经根据我在其中看到的内容重构了代码,并添加了一个余额计算器,但我还没有实际测试过它。

<?php

$sql = "SELECT name, doc_date, descs, debit, credit
        FROM statement
        WHERE  member_id = $member_id
        ORDER BY doc_date";

$query = mysql_query($sql);
$combinedResults = array();

// Slurp SQL results into array
while ($result = mysql_fetch_array($query)) {
  $combinedResults[$result['name']][] = array(
    'name' => $result['name'],
    'doc_date' => $result['doc_date'],
    'descs' => $result['descs'],'debit' => $result['debit'],
    'credit' => $result['credit']
  );
}

// Define a format for all table lines (add CSS as required)
$fmt = "<tr>\n  <td>%s</td>\n  <td>%s</td>\n  <td>%s</td>\n  <td>%s</td>\n  <td>%s</td>\n</tr>";

print "<style type='text/css'>TD{width:105px;}</style>\n";

print "<table>\n";

// Walk through array...
foreach ($combinedResults[$groupKey] as $item) {
  // Start a section...
  printf($fmt, "Date", "Description", "Debit", "Credit", "Balance");
  printf($fmt, $groupKey, "", "", "", "");
  $balance = 0; // Initialize the balance for this section...
  foreach ($combinedResults[$groupKey] as $item) {
    printf($fmt, $item['doc_date'], $item['descs'], $item['debit'], $item['credit'], "");
    $balance += $item['debit'];
  }
  printf($fmt, "", "", "", "", $balance); // Print the balance.
}

print "</table>\n";

我有兴趣知道它是否有效。:)

请注意,我没有考虑到您的“colspan”;我怀疑您应该先确定您的逻辑,然后再尝试将其构建到实际布局中。

于 2012-04-25T19:06:17.303 回答