Consider an array with a structure similar to the one below:
$array = [ [ 'id' => 2, 'type' => 'comment', 'text' => 'hey', 'datetime' => '2010-05-15 11:29:45', ], [ 'id' => 3, 'type' => 'status', 'text' => 'oi', 'datetime' => '2010-05-26 15:59:53', ], [ 'id' => 4, 'type' => 'status', 'text' => 'yeww', 'datetime' => '2010-05-26 16:04:24', ], ];
How can we sort this array by the 'datetime' element?
PHP's usort() function takes an array and a comparison function that determines the order of the elements. We can create a custom comparison function called date_compare as follows:
function date_compare($a, $b) { $t1 = strtotime($a['datetime']); $t2 = strtotime($b['datetime']); return $t1 - $t2; }
This function extracts the UNIX timestamp for the 'datetime' field of each record and returns the difference between them. This information is used by usort() to sort the array.
Finally, we can apply the sorting function to the array using usort():
usort($array, 'date_compare');
This will sort the array in ascending order based on the 'datetime' element.
The above is the detailed content of How to Sort a Multidimensional PHP Array by a Datetime Element?. For more information, please follow other related articles on the PHP Chinese website!