我有一个表,它使用foreach回显每个用户的一些SQL计数。我希望有一个总计将加起来所有的计数。任何想法都将不胜感激。
$students = get_course_students($course->id, 'lastname');
$toggle=0;
if (!empty($students)) {
foreach ($students as $student) {
$user=get_record('user','id',$student->id);
$atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
$personalcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 1 AND user = $user->id AND course = $course->id");
$reportscountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_reports WHERE user = $user->id AND course = $course->id");
echo '<tr class="r'.$toggle.'">
<td class="cell c'.$toggle.'" valign="top" nowrap="true" align="left">'.fullname($user).'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$atriskcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$personalcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$reportscountrecords.'</td>
</tr>';
if($toggle==0)$toggle=1;
else $toggle=0;
}
}
echo'<tr>
<td><strong>Totals</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td></td>
</tr>';
echo'</table>';
答案 0 :(得分:1)
如果我真的理解你的问题,那很简单;只需在foreach循环之前为每个计数器声明一个变量,并使用计数值增加它。 例如:
$atriskcountrecordsGlobal = 0;
if (!empty($students)) {
foreach ($students as $student) {
...
$atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
$atriskcountrecordsGlobal += $atriskcountrecords;
...
}