Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-11-06 00:17:02581browse

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>

Using usort:

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

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

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!

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