【问题标题】:How to get the sum of a column in while looping? [closed]如何在循环中获取列的总和? [关闭]
【发布时间】:2021-07-14 09:13:57
【问题描述】:

我有一个表使用 while 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

我想从每一行 ($totvs) 中得到 $totalvsc 的总和

代码的结果是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>

谁能帮帮我?

【问题讨论】:

  • 当你说它不起作用时,你会得到什么结果?
  • 结果是“6.66213.57820.72826.835”
  • number_format 返回字符串。仅用于显示
  • 表示 $vsc1,$vsc2,$vsc3,$vsc4 不使用 number_format ?
  • 你需要使用类型。就像@splash58 说的,number_format 返回字符串,所以需要使用float 类型进行添加。

标签: php arrays mysqli sum


【解决方案1】:

您应该将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>

【讨论】:

    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多