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条回答 默认 最新

相关推荐 更多相似问题