Computer >> 컴퓨터 >  >> 프로그램 작성 >> PHP

PHP에서 날짜 배열 정렬

<시간/>

PHP에서 날짜 배열을 정렬하는 코드는 다음과 같습니다-

예시

<?php
   function compareDates($date1, $date2){
      return strtotime($date1) - strtotime($date2);
   }
   $dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08");
   usort($dateArr, "compareDates");
   print_r($dateArr);
?>

출력

이것은 다음과 같은 출력을 생성합니다-

Array
(
   [0] => 2019-08-10
   [1] => 2019-09-08
   [2] => 2019-10-10
   [3] => 2019-11-11
)

예시

이제 다른 예를 살펴보겠습니다 -

<?php
   function compareDates($date1, $date2){
      if (strtotime($date1) < strtotime($date2))
         return 1;
      else if (strtotime($date1) > strtotime($date2))
         return -1;
      else
         return 0;
   }
   $dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01");
   usort($dateArr, "compareDates");
   print_r($dateArr);
?>

출력

이것은 다음과 같은 출력을 생성합니다-

Array
(
   [0] => 2019-11-11
   [1] => 2019-11-11
   [2] => 2019-10-10
   [3] => 2019-09-08
   [4] => 2019-05-11
   [5] => 2019-01-01
)