In a nutshell:
I want to create a list for students and grades. When I get my sql, I get many grades for the same student. What I'm trying to do is this:
Student 1 -> Grade 1 -> Grade 1 -> Grade 3
Student 2 -> Grade 1 -> Grade 2 -> Grade 3
My sql pulls all the records in the database which is great but how can I get it to display like this?
SQL is very standard
$query_getGradesTr1 = "SELECT gradeID, studentID, grades.examID, grade FROM grades, exams WHERE exams.trackID=1 AND grades.examID=exams.examID";
$getGradesTr1 = mysql_query($query_getGradesTr1, $Site) or die(mysql_error());
$row_getGradesTr1 = mysql_fetch_assoc($getGradesTr1);
$totalRows_getGradesTr1 = mysql_num_rows($getGradesTr1);
I thought about using a foreach to go through the results, basically foreach studentID give me all the grades associated with them and repeat for each students...
But I get multiple results with same StudentID then another studentID, like this:
Student 1 -> Grade 1
Student 1 -> Grade 2
Student 1 -> Grade 3
Student 2 -> Grade 1
Student 2 -> Grade 2
Student 2 -> Grade 3
Any suggestions??
Do this:
$current_student = NULL;
foreach($totalRows_getGradesTr1 as $each) {
// Check here is student does not matches to previous student
if($each->studentID !== $current_student) {
// If not matches then print, else ignore
echo "$each->studentID";
}
// Assign to check again in next loop
$current_student = $each->studentID;
// Always print grade
echo "-> $each->gradeID";
}
Another solution is, twice loop the array and make each studentId as array key assign all grades to the studentID, like:
$students_grades = array();
foreach($totalRows_getGradesTr1 as $each) {
if(!isset($student_grades[$each->studentID]) {
$student_grades[$each->studentID] = array();
}
$student_grades[$each->studentID][] = $each->gradeID;
}
// Then nested loop here and print records
foreach($student_grades as $studentID => $grades) {
echo "$studentID -> " . implode('->', $grades) . "<br>";
}