我有这段代码
<?php if($grades->subcompid==$subcomp->id && $grades->compid=='1' && $grades->termid=='1' && $grades->recordid==$recid && $grades->studentid==$student->studentid){
echo $grades->grade;
?>
我希望回显值20,25,14,12和45--上面的代码是这样做的。
问题是我想添加这些值以获得116所以我这样做了:
$midtermg = 0;
<?php if($grades->subcompid==$subcomp->id && $grades->compid=='1' && $grades->termid=='1' && $grades->recordid==$recid && $grades->studentid==$student->studentid){
$midtermg = $midtermg + $grades->grade;
echo $midtermg;
}
然而它返回值'20 45 59 71 116'。它将值添加到下一个值并回显每个值。我尝试了echo end($midtermg);
,但它说它不是一个数组,所以它不起作用。如果我只想让116回应怎么办?
* if语句返回正确的值,所以请不要介意
答案 0 :(得分:0)
喜欢这样。每次在if
内打印价值。只需在循环内汇总值。并在if
条件后打印。
<?php
$midtermg = 0;
if($grades->subcompid==$subcomp->id && $grades->compid=='1' && $grades->termid=='1' && $grades->recordid==$recid && $grades->studentid==$student->studentid){
$midtermg = $midtermg + $grades->grade;
}
echo $midtermg;
答案 1 :(得分:0)
初始化一个数组并将条件满足值推入数组,然后你可以使用这个数组。
<?php
$midtermg = 0;
$a_results= array();
if($grades->subcompid==$subcomp->id && $grades->compid=='1' && $grades->termid=='1' && $grades->recordid==$recid && $grades->studentid==$student->studentid){
// $midtermg = $midtermg + $grades->grade;
array_push($a_results, $grades->grade);
}
echo array_sum($a_results);