dongzhu7329 2016-08-04 13:13
浏览 85
已采纳

在关联数组中添加值

I'm new to php. This is my code

    $retval = $conn->query("Select points from evaluation_log where session_id='{$sessionid}';");
    $result=array();
    $temp=array();
    while($record = $retval->fetch_array(MYSQLI_ASSOC)) 
        {
            $result[]= $record;
        }

The purpose of this query is to return multiple points against an id from the database which i'm storing in an array. Now I want to take sum of these points in the array. How should I do that.

  • 写回答

3条回答 默认 最新

  • dongyan6910 2016-08-04 13:37
    关注

    If you absolutely must use your example then this would work:

    $retval = $conn->query("select points from evaluation_log where session_id='{$sessionid}'");
    
    $sum = 0;
    
    while($record = $retval->fetch_array(MYSQLI_ASSOC)) 
    {
        $sum+= $record['points'];
    }
    
    echo $sum;
    

    However, this should be simpler:

    $retval = $conn->query("select sum(points) as sum_points from evaluation_log where session_id='{$sessionid}'");
    
    $record = $retval->fetch_array(MYSQLI_ASSOC);
    
    echo $record['sum_points'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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