php - 使用 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?
}
?>
解决方案
首先修复此行,以便...您只能获得大于 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;
推荐阅读
- kubernetes - Kubernetes,在接受对 POD 的传入请求之前获取 API 令牌
- python - 为什么函数“len()”返回的答案比实际字符串长 1 个字符?
- java - 在java中将值从一个字符数组分配到另一个字符数组
- python - Cumsum 与 groupby
- python - TypeError: 'FirefoxWebElement' 对象是不可迭代的错误循环通过硒动态网页上的页面
- mongodb - MongoDB:对数组对象中的所有字段进行查询搜索
- mysql - Kubernetes 在卷中使用文件注入环境变量
- visual-studio - CMake 设置 Visual Studio 链接器 -> 命令行 -> 附加选项
- reactjs - 使用嵌套路由在 Apache HTTP 服务器上反应路由器
- timer - 在 VHDL 中生成第二个计数器