如何在foreach语句中加值(PHP)

例如,我有一个名为tbl_grade的表,其中包含以下数据

id   | studentid   |   compid   |  grade
1    | 1009123456  |     1      |  90
2    | 1009123457  |     2      |  95
3    | 1009123458  |     2      |  90

我的模型中有这行代码

public function gradeSum($studentid)
{
    $this->db->where('studentid',$studentid);
    $query = $this->db->get('tbl_grade');
    return $query->result();
}

在我看来:

<?php foreach ($this->UserModel->gradeSum($student->studentid) as $studentgrade):
   if($studentgrade->compid==2){
       echo $studentgrade->grade; //the code for the addition of the grades should be put here but for the meantime i just echoed the grades
   }
endforeach;?>

foreach语句会给我95和90,这是正确的。但我想重复一下它的总和。我放入了echo $sum->grade + $sum->grade;,但显然它不起作用,那么正确的语法是什么,这样我才能回显这些值的总和?

转载请注明出处:http://www.xiangbinbaiyi.com/article/20230510/1971094.html