How can time be considered as a secondary criteria in sorting results in PHP?
When sorting results in PHP, time can be considered as a secondary criteria by first sorting based on the primary criteria (such as alphabetical order or numerical value) and then sorting based on time. This can be achieved by using a custom sorting function that compares the primary criteria first and then the time. The custom sorting function should return a negative value if the first element should come before the second element, a positive value if the second element should come before the first element, and 0 if they are equal based on the primary criteria.
// Example array of results with primary criteria and time
$results = array(
array('name' => 'John', 'score' => 85, 'time' => '12:30'),
array('name' => 'Alice', 'score' => 92, 'time' => '11:45'),
array('name' => 'Bob', 'score' => 78, 'time' => '10:15')
);
// Custom sorting function to sort based on score and then time
usort($results, function($a, $b) {
if ($a['score'] == $b['score']) {
return strtotime($a['time']) - strtotime($b['time']);
}
return $a['score'] - $b['score'];
});
// Output sorted results
print_r($results);