php中while循环中的值和求和值

时间:2016-10-01 18:39:26

标签: php

我有一个查询返回mysql数据库中的行列表,生成的行列表中的行值相同。

Table
id    mAmount   paidAmount
1       100     50
1       100     30
2       200     20
2       200     150

我实际上想要对paidAmount求和,并从同一mAmount的{​​{1}}值中减去一个。

例如

id

我不希望任何人向我提供完整的代码,但想知道如何使用php with while循环或可能的foreach语句来解决它。非常感谢。

1 个答案:

答案 0 :(得分:0)

只需循环并累积付费金额,然后进行减法。 对于此示例,我假设您按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
        )
    )
相关问题