使用foreach循环将各列的总和相加并在表格底部显示每个总计

时间:2018-08-30 09:49:10

标签: php ms-access pdo

我有这个用于查询Microsoft Access数据库的foreach循环,但我不知道如何对具有值或无值的特定列求和并将表的最后一行的总和显示为“总计”。 / p>

这是我的代码:

$sql = "SELECT EmployeeName, BasisSalary, Bonus FROM tableEmployee";

if ($result = $connectdb->query($sql)) 
{
    $rows = '';             
    echo '<table>';   

    foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row) 
    {                 
        $heading = '';          
        $rows .= '<tr>'; 

        foreach($row as $key => $value) 
        {
            $limitwords = substr($value, 0,50);
            $heading .= '<th>'.$key.'</th>';
            $rows .= '<td>' . $limitwords . '</td>';
        }

        $rows .= '</tr>';
    }

    echo '<tr>'.$heading.'</tr>';
    echo $rows;

    echo '</table>';
}

我上面的代码将显示如下输出:

|EmployeeName|BasicSalary| Bonus |
|     A      |   10.00   | 10.00 |
|     B      |   20.00   | 10.00 |
|     C      |   30.00   | 10.00 |

所以我想像这样将总数显示为表格的最后一行:

|EmployeeName|BasicSalary| Bonus |
|     A      |   10.00   | 10.00 |
|     B      |   20.00   | 10.00 |
|     C      |   30.00   | 10.00 | 
|      Total |   60.00   | 30.00 |

1 个答案:

答案 0 :(得分:1)

保留两个变量$totalBasicSalary$totalBonus,以将两个字段的基本工资和奖金加起来。

修改后的代码:

$sql = "SELECT EmployeeName, BasisSalary, Bonus FROM tableEmployee";

if ($result = $connectdb->query($sql)) {
    $totalBasicSalary = $totalBonus = 0;
    echo '<table> '
    . ' <tr>'
    . '<th>EmployeeName</th>'
    . '<th>BasisSalary</th>'
    . '<th>Bonus</th>'
    . '</tr>';

    foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
        echo '<tr>'
        . '<td>' . substr($row["EmployeeName"], 0, 50) . '</td>'
        . '<td>' . $row["BasisSalary"] . '</td>'
        . '<td>' . $row["Bonus"] . '</td>'
        . '</tr>';

        $totalBasicSalary += $row["BasisSalary"];
        $totalBonus += $row["Bonus"];
    }

    echo '<tr>'
    . '<td>Total</td>'
    . '<td>' . $totalBasicSalary . '</td>'
    . '<td>' . $totalBonus . '</td>'
    . '</tr>'
    . '</table>';
}