让我解释一下背景故事,老师可以设置一个在场或缺席的学生。这些学生的价值被放在一个数据库中,这个查询选择课程代码并计算某一课程中学生的百分比,但是我有点坚持做什么,文件必须转换为JSON并放入ChartJS条形图但由于某种原因我似乎无法计算出这个代码,每个类都需要计算每个百分比,因此我不能使用IN或类似的东西来计算存在整个课程而不是每节课的课程(这就是klas.code =' $ klas'是什么意思)有谁知道我怎么能得到1个结果但仍然能够计算每个班级的百分比分开?
谢谢。
$klassen = array("WFHBOICT.V1E", "WFHBOICT.V1F");
foreach($klassen as $klas){
//query to get data from the table
$query = ("SELECT klas.code klas, ROUND(
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
AND aanwezigheid = '1'
)
/
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
)
* 100)
as percentage
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
JOIN vak ON college.Vcode = vak.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
GROUP BY klas.code");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
print json_encode($data);
结果如下:
[{"klas":"WFHBOICT.V1F","percentage":"67"}]
它必须在括号之间返回两个类而不仅仅是1 ...
答案 0 :(得分:2)
问题来自第一个foreach循环。在它之前初始化$ data数组并在打印之前关闭第一个foreach。
$klassen = array("WFHBOICT.V1E", "WFHBOICT.V1F");
$data = array();
foreach($klassen as $klas){
//query to get data from the table
$query = ("SELECT klas.code klas, ROUND(
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
AND aanwezigheid = '1'
)
/
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
)
* 100)
as percentage
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
JOIN vak ON college.Vcode = vak.code
WHERE klas.code = '".$klas."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
GROUP BY klas.code");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
foreach ($result as $row) {
$data[] = $row;
}
} // end first foreach
print json_encode($data);
希望它有所帮助。