我有一个数组的时间表:
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
显然,为了获得正确日期的字符串,我使用“foreach”和“if”,它返回正常。但那我该如何度过时光?
答案 0 :(得分:2)
Convert to timestamp,sort并与current time进行迭代比较。
$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]);
感兴趣的功能
答案 1 :(得分:0)
如果将这些转换为UNIX时间戳,则可以对它们进行数字排序,循环并获取大于当前时间戳的第一个项目。
答案 2 :(得分:0)
您可以考虑将这些日期转换为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
进行一些额外检查,确保它们在同一天或第二天,但是使用时间映射比较比使用字符串匹配更容易。< / p>
答案 3 :(得分:0)
为日期时间格式编写比较函数,然后循环,直到找到大于或等于参考日期的日期。
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;
}
$ dt1&lt;时返回-ve $ dt2&gt; $ dt1&gt; $ DT2