php,从数组中获取最接近电流的最高时间


php, get the the highest-closest time to current from array?

可能的重复项:
如何从日期数组中获取最近的日期?

我有一个时间表,它是一个数组:

array(
    '01.01.2012|11:00',
    '01.01.2012|14:30',
    '01.01.2012|16:24', // example match
    '01.01.2012|17:20',
    '01.01.2012|17:43',
    '02.01.2012|10:20',
    '02.01.2012|12:30',
); // etc.

我想要一个 Cron 作业,它将检查当前日期/时间并与数组中的日期/时间进行比较。首先我检查日期是否匹配,没问题。但是,我需要从该数组中找到并显示当前时间之后的最早时间。如果同一日期内没有合适的时间,那么我会显示下一个日期的最早时间。

例如:让我们取上面的数组和当前日期/时间01.01.2012|14:45

  • 日期是匹配的,所以我们继续
  • 下一次从数组 16:24,但是如何使用 PHP 找到它?如果当前时间高于数组中同一日期的任何时间,那么从下一个日期获取最早的时间?

显然,为了获得具有正确日期的字符串,我使用"foreach"和"if",它返回正常。但是,我该如何度过时代呢?

转换为时间戳,排序并与当前时间迭代比较。

$ts = array_map(
        create_function('$a','return strtotime(str_replace("|", " ", $a));'), 
        $dates);
$len= count($ts); $now = time();
sort($ts); 
for($i=0;$i<$len && (!($now<$ts[$i]));$i++);
echo date("d.m.Y|H:i",$ts[$i]);

感兴趣的功能

  • array_map
  • create_function
  • str_replace

如果将它们转换为 UNIX 时间戳,则可以按数字方式对它们进行排序,遍历并获取大于当前时间戳的第一项。

您可以考虑将这些日期转换为 UNIX 时间戳:

function getUnixTimestamp($string) {
    list($date, $time) = explode('|', $string);
    return strtotime("$date $time");
}

然后你可以使用类似的东西:

$array = array(); // from example
$timestamps = array_map('getUnixTimestamp', $array);
$current = time();
// create an array mapping timestamp to string
$keyedArray = array_combine($timestamps, $array);
// sort by timestamp
ksort($keyedArray);
foreach ($keyedArray as $timestamp => $string) {
    if ($timestamp > $current) {
        // this is the first timestamp after current time
    }
}

您可能想对$timestamp进行一些额外的检查,确保它在同一天或第二天,但与字符串匹配相比,使用 timestmap 比较更容易。

为日期时间格式编写一个比较函数,然后循环访问,直到找到大于或等于参考日期的日期。

function compareDateTime($dt1, $dt2) {
   sscanf($dt1, "%d.%d.%d|%d:%d", $day, $month, $year, $hour, $minute);
   $comp1 = $year . $month . $day . $hour . $minute;
   sscanf($dt1, "%d.%d.%d|%d:%d", $day, $month, $year, $hour, $minute);
   $comp2 = $year . $month . $day . $hour . $minute;
   return $comp1 - $comp2;
}

当 $dt 1 <$dt 2 时返回 -ve,在 $dt 1> $dt 2 时返回 +ve