我有一个从mysql数据库返回行列表的查询,生成的行列表中的行值是相同的。
Table
id mAmount paidAmount
1 100 50
1 100 30
2 200 20
2 200 150我实际上想要对paidAmount求和,并从每个相同id的mAmount值中减去一个值。
例如
1 | (100) - (50 + 0) = 50 |
1 | (100) - (30 + 50) = 20 |
2 | (200) - (20 + 0) = 180 |
2 | (200) - (150 + 20) = 30 |我不希望任何人给我的完整代码,但如何使用php的while循环或可能的foreach语句的想法。谢谢,真的很感谢。
发布于 2016-10-02 03:06:00
只需循环并累加支付金额,然后进行减法。在本例中,我假设您按id对记录进行了预排序,并将记录传递给一个名为rows的多维数组:
$currentId = $rows[0]['id'];
$accumulated = 0;
foreach ( $rows as $row ) {
if ( $row['id'] != $currentId ) {
$accumulated = 0;
$currentId = $row['id'];
} // end if not current id
$accumulated += $row['paidAmount'];
$balance = $row['mAmount'] - $accumulated;
$row['balance'] = $balance;
$result[] = $row;
} // end foreach
print_r ( $result );结果打印如下:
Array
(
[0] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 50
[balance] => 50
)
[1] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 30
[balance] => 20
)
[2] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 20
[balance] => 180
)
[3] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 150
[balance] => 30
)
)https://stackoverflow.com/questions/39810213
复制相似问题