Suppose we have an event array, the key is a timestamp, and the value is an event description:
<?php
$events = [
1685702400 => 'eventAoccur',
1685788800 => 'eventBoccur',
1685616000 => 'eventCoccur',
];
// use krsort Press the array key(Timestamp)Sort in reverse order
krsort($events);
foreach ($events as $timestamp => $event) {
echo date('Y-m-d H:i:s', $timestamp) . " - $event\n";
}
?>
Running results:
2023-06-03 00:00:00 - eventBoccur
2023-06-02 00:00:00 - eventAoccur
2023-06-01 00:00:00 - eventCoccur
With krsort , events are arranged in reverse order in time, with the latest events at the forefront.
Sometimes events are not just simple descriptions, but contain multiple fields, such as titles, contents, etc. We can still use timestamps as keys to outer arrays to facilitate the use of krsort .
<?php
$events = [
1685702400 => [
'title' => 'eventA',
'content' => 'eventADetails of',
],
1685788800 => [
'title' => 'eventB',
'content' => 'eventBDetails of',
],
1685616000 => [
'title' => 'eventC',
'content' => 'eventCDetails of',
],
];
krsort($events);
foreach ($events as $timestamp => $event) {
echo date('Y-m-d H:i:s', $timestamp) . " - {$event['title']}: {$event['content']}\n";
}
?>
You can also get a list of events arranged in reverse order in time.
krsort is sorted in reverse according to the array key name, suitable for timestamp sorting.
When using timestamps as array keys, krsort can quickly implement reverse order arrangement.
Event records can be simple strings or complex structures, both krsort are suitable.
After sorting, you can use foreach to traverse and output first according to the latest event.
With krsort mastered, you can more flexibly process time-based data in reverse order, which is convenient for developing functions such as log system and timeline display.