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 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能