Royal Posted July 19, 2023 Share Posted July 19, 2023 <?php // Assuming you have a database connection established // Fetch student records from the database $query = "SELECT * FROM students"; $result = mysqli_query($connection, $query); // Create an empty array to store the student records $students = []; // Check if the query was successful and fetch the data if ($result) { while ($row = mysqli_fetch_assoc($result)) { $students[] = $row; } } else { // Handle the query error echo "Error: " . mysqli_error($connection); } // Sort the students array based on totalexamscore in descending order usort($students, function ($a, $b) { if ($a['totalexamscore'] === $b['totalexamscore']) { return 0; } return ($b['totalexamscore'] > $a['totalexamscore']) ? 1 : -1; }); // Calculate the position of each student $position = 1; $prevScore = null; foreach ($students as &$student) { if ($student['totalexamscore'] !== $prevScore) { $prevScore = $student['totalexamscore']; $student['position'] = $position; } $position++; } // HTML table generation echo '<table>'; echo '<tr> <th>Student ID</th> <th>Name</th> <th>Total Exam Score</th> <th>Subject 1 Test Score</th> <th>Subject 1 Exam Score</th> <th>Subject 2 Test Score</th> <th>Subject 2 Exam Score</th> <th>Subject 3 Test Score</th> <th>Subject 3 Exam Score</th> <th>Position</th> </tr>'; foreach ($students as $student) { echo '<tr>'; echo '<td>' . $student['student_id'] . '</td>'; echo '<td>' . $student['student_name'] . '</td>'; echo '<td>' . $student['totalexamscore'] . '</td>'; echo '<td>' . $student['subject1testscore'] . '</td>'; echo '<td>' . $student['subject1examscore'] . '</td>'; echo '<td>' . $student['subject2testscore'] . '</td>'; echo '<td>' . $student['subject2examscore'] . '</td>'; echo '<td>' . $student['subject3testscore'] . '</td>'; echo '<td>' . $student['subject3examscore'] . '</td>'; echo '<td>' . $student['position'] . '</td>'; echo '</tr>'; } echo '</table>'; // Close the database connection mysqli_close($connection); ?> Please i need to know if the code above will be able to sort the array results , calculate positions based on totalexamscore and also create a tie position for students with same score. Quote Link to comment Share on other sites More sharing options...
Barand Posted July 19, 2023 Share Posted July 19, 2023 The best way to find out is to test it. Run it Check it This looks like deja vu! https://forums.phpfreaks.com/topic/317078-issue-generating-student-class-position-based-on-the-grand-exam-score/?do=findComment&comment=1610463 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.