从日期附近的日期数组中选择

时间:2016-02-26 12:52:13

标签: php arrays sorting date usort

我有阵列

Array
(
    [0] => 2016-02-22 00:20:00
    [1] => 2016-02-25 08:45:00
    [2] => 2016-02-25 19:10:00
    [3] => 2016-02-25 20:00:00
    [4] => 2016-02-26 15:55:00
    [5] => 2016-02-28 17:10:00
)

如何找到距离当前日期最近的日期?

2 个答案:

答案 0 :(得分:2)

//Start with your array
$array = ["2016-02-22 00:20:00", "2016-02-25 08:45:00", "2016-02-25 19:10:00", "2016-02-25 20:00:00", "2016-02-26 15:55:00", "2016-02-28 17:10:00", "2016-01-22 00:00:00"];

//Set an array called $closestTime that has the time difference and the key
$closestTime = [null,null];

//Check each element in array
foreach($array as $key => $date){

    //Calculate difference between now and the time in seconds
    $diff = strtotime("now") - strtotime($date);;
    if($diff<0) $diff = $diff * -1; 

    //If $closestTime is empty, populate it
    if($closestTime[0]===null) $closestTime = [$diff,$key];

    //If $closestTime isn't empty and the current date's time difference
    //is smaller, populate $closestTime with the time difference and key
    elseif($diff < $closestTime[0]) $closestTime = [$diff,$key];
}

//Print the closest time
echo $array[$closestTime[1]];

//Outputs:
//2016-02-26 15:55:00

答案 1 :(得分:1)

简单:转换为时间戳,减去搜索到的时间戳并取绝对值,找到最小值。

快速,假设排序的时间戳数组:使用二进制搜索找到第一个更大的元素,比较距离该元素的距离与距前一个元素的距离,选择一个距离较小的元素;如果没有元素更大,则选择最后一个元素;如果第一个元素已经更大,则选择第一个元素。