In this article, we will introduce to you how to use PHP to arrange a date array (an array composed of multiple dates in Ymd format) in descending order.
To solve this problem in C/c/Java or any other general purpose programming language, we have to compare the dates based on year, month and last number of days or convert the dates Store in any structure, or in any other desired data structure.
But in PHP, if you apply the strtotime() function, this problem seems to be very simple. The strtotime() function is a PHP function that changes the given date in any format into a timestamp, which is essentially a big integer. Then while sorting the array, we can define a comparator function by Easily use PHP | usort() function. The comparator function will accept two date parameters, which will be converted to integer timestamps using the strtotime() function and then compared to a sorted date based on the integer timestamp value.
Built-in functions used:
strtotime(): This function changes the given date string to a timestamp (large int value).
usort(): This function sorts the given array based on a user-defined comparison function.
The PHP code implementation example is as follows:
<?php function compareByTimeStamp($time1, $time2) { if (strtotime($time1) < strtotime($time2)) return 1; else if (strtotime($time1) > strtotime($time2)) return -1; else return 0; } $arr = array("2019-03-12", "2012-09-06", "2018-09-09"); usort($arr, "compareByTimeStamp"); print_r($arr);
Output:
Array ( [0] => 2019-03-12 [1] => 2018-09-09 [2] => 2012-09-06 )
Related recommendations: "PHP Tutorial"
This article is an introduction to the method of sorting date arrays in PHP. It is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to sort date array in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!