John Davidson

php - How do I get the number of times a grade appears

0 comments
Message:


I'm trying to display the number of times each grade appears in a student's report sheet.


grades


In this image, the student has 5Bs and 2Cs.
How do I display it?


This is how I got the grades


<?php $i = 1;
$total = 0;
$count = count($subjectScores);
foreach ($subjectScores as $value) { ?>
<?php

if ($value->tot_score >= 90 && $value->tot_score <= 100) {
$grade = 'A+';
$remark = 'DISTINCTION';
} elseif ($value->tot_score >= 80 && $value->tot_score <= 89.99) {
$grade = 'A';
$remark = 'EXCELLENT';
} elseif ($value->tot_score >= 70 && $value->tot_score <= 79.99) {
$grade = 'B+';
$remark = 'VERY GOOD';
} elseif ($value->tot_score >= 60 && $value->tot_score <= 69.99) {
$grade = 'B';
$remark = 'GOOD';
} elseif ($value->tot_score >= 50 && $value->tot_score <= 59.99) {
$grade = 'C';
$remark = 'ABOVE AVERAGE';
} elseif ($value->tot_score >= 45 && $value->tot_score <= 49.99) {
$grade = 'D';
$remark = 'AVERAGE';
} elseif ($value->tot_score >= 40 && $value->tot_score <= 44.99) {
$grade = 'E';
$remark = 'FAIR';
} elseif ($value->tot_score >= 0 && $value->tot_score <= 39.99) {
$grade = 'F';
$remark = 'NEEDS IMPROVEMENT';
}
?>

<?php
$total += $value->tot_score;

?>

//modified here

<?php
$eachgrade = array($grade);
$gradenum = array_count_values($eachgrade);
foreach ($gradenum as $key=>$gvalue) {
echo $key ."=". $gvalue;
}
?>

My output is
C=1 B=1 B=1


It should be
C=1 B=2



My Answer:
To get the correct count of each grade, you need to modify the code as follows:

php
$grades = array(); // Initialize an empty array to store grades

foreach ($subjectScores as $value) {
if ($value->tot_score >= 90 && $value->tot_score <= 100) {
$grade = 'A+';
} elseif ($value->tot_score >= 80 && $value->tot_score <= 89.99) {
$grade = 'A';
} elseif ($value->tot_score >= 70 && $value->tot_score <= 79.99) {
$grade = 'B+';
} elseif ($value->tot_score >= 60 && $value->tot_score <= 69.99) {
$grade = 'B';
} elseif ($value->tot_score >= 50 && $value->tot_score <= 59.99) {
$grade = 'C';
} elseif ($value->tot_score >= 45 && $value->tot_score <= 49.99) {
$grade = 'D';
} elseif ($value->tot_score >= 40 && $value->tot_score <= 44.99) {
$grade = 'E';
} elseif ($value->tot_score >= 0 && $value->tot_score <= 39.99) {
$grade = 'F';
}

// Add the grade to the grades array
if(isset($grades[$grade])){
$grades[$grade]++;
} else {
$grades[$grade] = 1;
}
}

// Display the count of each grade
foreach ($grades as $key => $value) {
echo $key . "=" . $value . " ";
}
?>


This code will correctly count the number of times each grade appears in the student's report sheet and display it as expected.

Rate this post

3 of 5 based on 5587 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us