Home  >  Article  >  Backend Development  >  How to sort PHP date array

How to sort PHP date array

藏色散人
藏色散人Original
2019-01-30 14:16:367447browse



There is such an array, which is composed of multiple dates in (Y-m-d) format. How can we write a program using PHP to sort all dates appearing in an array in descending order?

How to sort PHP date array

So if we solve this problem in C/c/Java or any other general programming language, we have to compare the date based on year, month and finally based on day, the method is Store the date in any structure or any other data structure you need.

But in PHP, we can use the strtotime() function, and this problem can be easily solved.

strtotime() function is a PHP function that changes a given date in any format into a timestamp which is essentially a big integer and then while sorting the array we can pass Define a comparison function easily using 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 with a date sort 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 following is the PHP code implementation of the above idea:

<?php 
//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("2018-09-12", "2019-09-06", "2019-09-09"); 
  
// 使用给定的用户定义函数对数组排序
usort($arr, "compareByTimeStamp"); 
  
print_r($arr); 
  
?>

Output:

Array 
( 
    [0] => 2019-09-09 
    [1] => 2019-09-06 
    [2] => 2018-09-12
)

This article is about the method of sorting PHP date arrays, which is also very simple and easy I understand, I hope it helps those in need!



The above is the detailed content of How to sort PHP date array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn