dongqin1861 2011-11-27 12:16
浏览 12
已采纳

如何总结数组变量中的值?

I have retrieved some values from database. In my view file I have the following:

 $row['fee_amount']; 

Now, I want to sum up all the values inside $row['fee_amount']; and then show it.

I know I could sum up when querying the database, but I am interested to learn how to add using PHP .

Would you please kindly teach me how to do it?

EDIT

    <?php if(count($records) > 0) { ?>              
        <table id="table1" class="gtable sortable">
            <thead>
                <tr>                        
                    <th>S.N</th>
                    <th>Fee Type</th>
                    <th>Fee Amount</th>                         
                </tr>
            </thead>
            <tbody>             
                <?php $i = 0; foreach ($records as $row){ $i++; ?>
                    <tr>
                        <td><?php echo $i; ?>.</td>
                        <td><?php echo $row['fee_type'];?></td>                                                
                        <td><?php echo $row['fee_amount'];?></td>                                           
                    </tr>                                                                                          
                <?php  } ?>             
            </tbody>                
            <tr>                                                        
                <td></td>
                <td>Total</td>
                <td> 
                    I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <?  $row['fee_amount']; ?> 
                </td>                                                                               
            </tr>               
        </table>
    <?php } ?>
  • 写回答

4条回答 默认 最新

  • dter8514 2011-11-27 15:12
    关注

    In your view file, with your foreach loop, add a $sum variable next to your $i counter and add the amount per each iteration (similar to like you increase $i):

    <?php
        $i = 0;
        $sum = 0;
        foreach ($records as $row)
        { 
            $i++; 
            $sum += $row['fee_amount']; ?>
    

    (I put this over multiple lines to make it more readable).

    After the foreach has finished, $sum contains the total amount:

            <td>Total: <?php echo $sum; ?></td>
    

    That simple it is. You only need a new variable ($sum) and do the calculation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题