php - 从日期数组中选择接近日期的日期

标签 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
)

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

最佳答案

//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

关于php - 从日期数组中选择接近日期的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35652244/

相关文章:

php - 左连接且属于

php - jQuery 和 MySQL

php - php 和 MySQL 中简单的喜欢/不喜欢评级系统

java - 使用java中的选择排序按字符串对用户定义的数组进行排序

javascript - 返回函数的值而不是 Array.forEach 中的内部函数

c++ - 在 C++ 中对多维数组进行排序

PHP - 将动态字段保存到 MySQL 数据库

java - 在 ByteArray 中查找字节序列

.net - 如何对 . .NET 中的 resx(资源文件)

linux - 如何在 bash 中对逗号分隔值进行排序?