【问题标题】:Add sum of each column and display each total in the bottom of the table using foreach loop使用 foreach 循环添加每列的总和并在表格底部显示每个总计
【发布时间】:2018-08-30 09:49:10
【问题描述】:

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

这是我的代码:

$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 |

【问题讨论】:

    标签: php ms-access pdo


    【解决方案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>';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      相关资源
      最近更新 更多