Home  >  Article  >  Backend Development  >  How to sort timestamps in an array, preserving key names, using PHP?

How to sort timestamps in an array, preserving key names, using PHP?

WBOY
WBOYOriginal
2024-05-03 22:36:01713browse

You can sort the array through the uasort() function, retaining its key names. To sort based on timestamps, you can use the custom comparison function compare_timestamps, which compares the timestamp fields in elements. In the actual case, this comparison function is used to sort the timestamps in the array, retaining the key names, and output the sorted array from small to large.

如何使用 PHP 对数组中的时间戳进行排序,保留键名?

Sort the array by timestamp in PHP, retaining the key names

In PHP, we can use uasort() Function sorts an array while preserving its key names. This is the syntax for sorting an array:

uasort($array, $sort_function);

where $array is the array to be sorted and $sort_function is the user-defined comparison function.

Sort comparison function

The sort comparison function must follow a specific format:

function sort_function(mixed $a, mixed $b): int

It needs to accept two parameters, $a and $b, these parameters represent the array elements to be compared. The function should return the following value:

  • -1: if $a should come before $b.
  • 0: If $a and $b are equal.
  • 1: If $a should come after $b.

Sort based on timestamp

To sort an array based on timestamp, we can use the following sort comparison function:

function compare_timestamps(mixed $a, mixed $b): int
{
    return $a['timestamp'] - $b['timestamp'];
}

This The function compares the timestamp fields in the array elements and returns the appropriate value to place the elements in order.

Practical case

The following is a practical case of using our sorting function to sort the timestamps in an array:

$array = [
    'item1' => ['timestamp' => 1593475200],
    'item2' => ['timestamp' => 1601260800],
    'item3' => ['timestamp' => 1584230400],
];

uasort($array, 'compare_timestamps');

print_r($array);

Output:

Array
(
    [item3] => Array
        (
            [timestamp] => 1584230400
        )

    [item1] => Array
        (
            [timestamp] => 1593475200
        )

    [item2] => Array
        (
            [timestamp] => 1601260800
        )
)

As you can see, the array has been sorted in timestamp order while preserving the key names.

The above is the detailed content of How to sort timestamps in an array, preserving key names, using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn