Home > Article > Backend Development > 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!