这里有人可以帮我解决这个问题吗?我只想获得某列的总数或总和,请参考下图。一直在尝试排序这个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"> </td>
<td width="105"> </td>
<td width="105"> </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> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td>sum of debit goes here</td>
</tr>
<?php }} ?>
</table>
答案 0 :(得分: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']; ?>
您可能还希望查看替换mysql_
函数的PDO和prepared statements。
答案 1 :(得分: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”;我怀疑在你尝试将它构建成一个实际的布局之前,你应该坚持自己的逻辑。