Home > Article > Backend Development > How Can I Sort a Multidimensional Array in PHP Based on a Unix Timestamp?
Sorting a Multidimensional Array in PHP
Objective
To sort a multidimensional array based on the unix timestamp stored in the sub-array "x".
Solution
To achieve this, you can utilize a custom comparison function in conjunction with the usort function.
Custom Comparison Function
<code class="php">function compare($x, $y) { if ($x[4] == $y[4]) return 0; else if ($x[4] < $y[4]) return -1; else return 1; }</code>
Applying the Function with usort
<code class="php">usort($arrayOfArrays, 'compare');</code>
Further Clarification
The usort function expects a comparison function as its second argument, which takes two elements from the array and returns a negative value if the first element should be placed before the second element, a zero value if they should appear in the same order, and a positive value if the first element should be placed after the second element.
This custom function compares the unix timestamp values in the fourth position of each sub-array. If the timestamps are equal, it returns 0. If the first timestamp is earlier than the second, it returns -1. Otherwise, it returns 1, indicating that the second sub-array should appear after the first.
The above is the detailed content of How Can I Sort a Multidimensional Array in PHP Based on a Unix Timestamp?. For more information, please follow other related articles on the PHP Chinese website!