首页 > 解决方案 > 使用 php 对所有学生取一门学科的平均值

问题描述

我有一个包含一门学科的学生的 SQL 表。我想对这个特定学科的所有学生取平均值,这样:

Sum of the subject/Number of total students

该表如下所示:


Student ID : 1
=============
Maths : 40

Student ID : 2
=============
Maths : 60

Student ID : 3
=============
Maths : 90

Student ID : 4
=============
Maths : 0

因此,如果学生得分为 0,则在计算平均值时忽略该学生及其分数。

<?php 
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

$db = new PDO("mysql:host=localhost; dbname=db;charset=utf8",'user','');
$sql = "SELECT * FROM Students";
$stmt = $db->query($sql);

while($data = $stmt->fetch(PDO::FETCH_OBJ)){
 //How to take the mean of 1 subject for all students?
}
?>

标签: phpmysql

解决方案


首先修复此行,以便...您只能获得大于 0 的分数

$sql = "SELECT * FROM students WHERE subjectscore > 0"; //assuming your column for scores is "subjectscore"

获得均值的其余代码应该是

$stmt = $db->query($sql);

while($data = $stmt->fetch(PDO::FETCH_OBJ)){

                 $sumparts .= $data->subjectscore."+"; //Add a delimiter after every returned obj

                                           }

print_r($sumparts); //For debug :to see which ones are selected

$sumarr = explode("+",$sumparts); // Convert the delimited string to array
    $sum = array_sum($sumarr); //Get sum of values of array in this case the scores
    $divisor = count($sumarr) - 1; //The minus 1 is necessary since well the delimited string will always have 1 extra key therefore making the count to count 1 more unnnecessary key 

$total = $sum/$divisor; //Sum of all divided by the total number of objects

echo $total;

推荐阅读