我正在使用php并具有以下结构
<?php if(!empty($bids)): ?>
<?php foreach ($bids as $bid):?>
<tr>
<td><?php if($bid['Bid']['debit'] > 0) : ?><?php echo $bid['Bid']['debit']; ?><?php else: ?> <?php endif; ?></td>
<td><?php if($bid['Bid']['credit'] > 0) : ?><?php echo $bid['Bid']['credit']; ?><?php else: ?> <?php endif; ?></td>
</tr>
<?php endforeach; ?>
<?php endif;?>
现在我需要计算每种情况下的总和。我知道这很容易,但没有得到如何在foreach
内使用循环来计算总价值。请建议如何进行循环。
如果假设第一个td
样本输出结构如下所示,我需要加起来只显示22而不是数组
0 2 0 20
答案 0 :(得分:4)
尝试:
<?php
if(!empty($bids)) {
$debitSum = 0;
$creditSum = 0;
foreach ($bids as $bid) {
$debit = $bid['Bid']['debit'];
$credit = $bid['Bid']['credit'];
echo '<tr>';
echo '<td>' . ( $debit > 0 ? $debit : ' ' ) . '</td>';
echo '<td>' . ( $credit> 0 ? $credit : ' ' ) . '</td>';
echo '</tr>';
$debitSum += $debit;
$creditSum += $credit;
}
echo '<tr style="font-weight: bold">';
echo '<td>' . $debitSum . '</td>';
echo '<td>' . $creditSum . '</td>';
echo '</tr>';
}
?>
编辑:
如果$bid['Bid']['debit']
(或信用额度)是字符串值,则将其强制转换为int值:
$debit = (int) $bid['Bid']['debit'];
答案 1 :(得分:1)
为什么不在foreach之外添加一个计数器变量?
<?php
$total['debit'] = 0;
$total['credit'] = 0;
foreach ((array)$bids as $bid)
{
$debit = ($bid['Bid']['debit'] > 0)? $bid['Bid']['debit'] : 0;
$credit = ($bid['Bid']['credit'] > 0)? $bid['Bid']['credit'] : 0;
$total['debit'] += $debit;
$total['credit'] += $credit;
$output =<<<XHTML
<tr>
<td>{$debit}</td>
<td>{$credit}</td>
</tr>
XHTML;
echo $output;
}
?>
答案 2 :(得分:0)
最好在循环内定义变量并将值添加到变量中,然后打印变量。