我有一个名为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;
但显然它没有用,所以正确的语法是什么,以便我可以回显值的总和?
答案 0 :(得分:1)
只需使用temp var进行添加
<?php
$mySum = 0;
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
$mySum = $mySum + $studentgrade->grade;
}
endforeach;
echo $mySum;
?>