Home > Backend Development > PHP Tutorial > How do I sort a multidimensional array by its UNIX timestamp value?

How do I sort a multidimensional array by its UNIX timestamp value?

DDD
Release: 2024-11-06 00:17:02
Original
689 people have browsed it

How do I sort a multidimensional array by its UNIX timestamp value?

Sorting a Multidimensional Array by UNIX Timestamp Value

The given multidimensional array requires sorting based on the UNIX timestamp value stored in the fourth index of each subarray. To achieve this, a user-defined comparison function can be employed.

Comparison Function:

The compare function should compare the UNIX timestamp values and return an integer indicating their order:

<code class="php">function compare($x, $y) {
    if ($x[4] == $y[4]) {
        return 0;
    } elseif ($x[4] < $y[4]) {
        return -1;
    } else {
        return 1;
    }
}</code>
Copy after login

Using usort:

The usort function is used to sort the array using the comparison function:

<code class="php">usort($nameOfArray, 'compare');</code>
Copy after login

By passing the comparison function as the second argument to usort, it will sort the array by ascending order of the UNIX timestamp values. The sorted result will be stored back in the original array, $nameOfArray.

The above is the detailed content of How do I sort a multidimensional array by its UNIX timestamp value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template