Home >Backend Development >PHP Tutorial >How Can I Sort a Multidimensional PHP Array by Date?
Consider an array of arrays, where each inner array (record) contains a "datetime" element in YYYY-MM-DD HH:MM:SS format. The task is to sort the records within the array in ascending or descending order based on this date.
To address this, the usort() function provides a versatile solution:
function date_compare($a, $b) { $t1 = strtotime($a['datetime']); $t2 = strtotime($b['datetime']); return $t1 - $t2; }
Here, the date_compare() function extracts UNIX timestamps from the "datetime" fields of the compared records. The difference between these timestamps determines the sorting order.
usort($array, 'date_compare');
By passing the array to usort() with the date_compare() function as the comparison callback, the records will be sorted according to the extracted timestamps. This approach is convenient and efficient for ordering multidimensional arrays by date elements.
The above is the detailed content of How Can I Sort a Multidimensional PHP Array by Date?. For more information, please follow other related articles on the PHP Chinese website!