如何在循环时获取列的总和?

How to get the sum of a column in while looping?

我有一个 table 在 MySQLi 获取数组时使用:

C1 C2 C3 C4 Total
$vsc1 $vsc2 $vsc3 $vsc4 $totalvsc // 6.662
$vsc1 $vsc2 $vsc3 $vsc4 $totalvsc // 6.916
$vsc1 $vsc2 $vsc3 $vsc4 $totalvsc // 7.15
$vsc1 $vsc2 $vsc3 $vsc4 $totalvsc // 6.107
-- -- -- Total Vektor S sum of $totalvsc ($totvs) // 6.66213.57820.72826.835

我想从每一行中获取 $totalvsc 的总和 ($totvs)

代码的结果是6.66213.57820.72826.835.
结果应该不是这个,而是26.835.

我已经试过了,但是没有用。这是代码:

<tr>
   <th colspan="7">Total Vektor S</th>
      <td>
         <?php
            $totvs = 0;
            $sql2 = mysqli_query($koneksi,"select * from tb_alternatif");
            while ($hasil1 = mysqli_fetch_array($sql2))
            {
               $vsc1 = number_format(pow((int)$hasil1[2],$nb1),3);
               $vsc2 = number_format(pow((int)$hasil1[3],-$nb2),3);
               $vsc3 = number_format(pow((int)$hasil1[4],$nb3),3);
               $vsc4 = number_format(pow((int)$hasil1[5],-$nb4),3);
               $totalvs = $vsc1 + $vsc2 + $vsc3 + $vsc4;
               $totvs += $totalvs;
               echo $totvs; 
            }
       ?>
   </td>
</tr>

谁能帮帮我?

您应该将 echo 放在 while 循环之外,您当前的代码在每个循环周期中打印总变量的累积,这就是输出奇怪的原因。

<tr>
   <th colspan="7">Total Vektor S</th>
      <td>
         <?php
            $totvs = 0;
            $sql2 = mysqli_query($koneksi,"select * from tb_alternatif");
            while ($hasil1 = mysqli_fetch_array($sql2))
            {
               $vsc1 = number_format(pow((int)$hasil1[2],$nb1),3);
               $vsc2 = number_format(pow((int)$hasil1[3],-$nb2),3);
               $vsc3 = number_format(pow((int)$hasil1[4],$nb3),3);
               $vsc4 = number_format(pow((int)$hasil1[5],-$nb4),3);
               $totalvs = $vsc1 + $vsc2 + $vsc3 + $vsc4;
               $totvs += $totalvs;
            }
            echo $totvs;
       ?>
   </td>
</tr>