dqc18251 2015-09-10 19:56
浏览 57
已采纳

如何在PHP中按日期间隔对数组进行排序

I have an array that contains date values. I want to sort this array by date, where the date is near(+/-1 days) from now date. The array is in this format:

Array
(
   [0] => Array
    (
        [id] => 4197
        [date] => Wed, 19 Sep 2015 17:00:00 +0000
    )
    [1] => Array
        (
            [id] => 4192
            [date] => Sun, 13 Sep 2015 17:00:00 +0000
        )
    [2] => Array
        (
            [id] => 4189
            [date] => Sat, 29 Aug 2015 20:00:00 +0000
        )
    [3] => Array
        (
            [id] => 4173
            [date] => Wed, 09 Sep 2015 16:00:00 +0000
        )
)

I want to get the array sorted in this way:

Array
(
   [0] => Array
    (
            [id] => 4173
            [date] => Wed, 09 Sep 2015 16:00:00 +0000
    )
    [1] => Array
        (
            [id] => 4192
            [date] => Sun, 13 Sep 2015 17:00:00 +0000
        )
    [2] => Array
        (
            [id] => 4197
            [date] => Wed, 19 Sep 2015 17:00:00 +0000
        )
    [3] => Array
        (
            [id] => 4189
            [date] => Sat, 29 Aug 2015 20:00:00 +0000
        )
)

I tried this solution:

function sortFunction( $a, $b ) {
    $now = strtotime("+1 day");
    if (($now - strtotime($a["date"])>0) && ($now - strtotime($b["date"])<0))
     {return 0;}
    return strtotime($b["date"]) - strtotime($a["date"]);
}
usort($array, "sortFunction");

what I'm doing wrong. Thanks

  • 写回答

1条回答 默认 最新

  • dongmu6225 2015-09-10 20:15
    关注

    Assuming all of inner arrays have a date property with the value formatted consistently, the following solution works:

    usort($array, function($dateArray1, $dateArray2) {
    
            $now = new \DateTime();
    
            $dateA = new \DateTime($dateArray1['date']);
            $dateB = new \DateTime($dateArray2['date']);
    
            $dayDifferenceA = abs($dateA->diff($now)->days);
            $dayDifferenceB = abs($dateB->diff($now)->days);
    
            if($dayDifferenceA == $dayDifferenceB) {
                return 0;
            }
    
            return ($dayDifferenceA < $dayDifferenceB) ? -1 : 1;
        });
    

    More checks should be added to ensure date calculations produce correctly formatted results throughout but this is the code in its most basic form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?