sug*_*ari 23 php arrays date date-comparison
我在下面列出了一系列日期
array(5) {
[0]=> string(19) "2012-06-11 08:30:49"
[1]=> string(19) "2012-06-07 08:03:54"
[2]=> string(19) "2012-05-26 23:04:04"
[3]=> string(19) "2012-05-27 08:30:00"
[4]=> string(19) "2012-06-08 08:30:55"
}
Run Code Online (Sandbox Code Playgroud)
并且想知道最近的日期:最接近今天的日期.
我怎样才能做到这一点?
flo*_*ree 71
使用max(),array_map()和strtotime().
$max = max(array_map('strtotime', $arr));
echo date('Y-m-j H:i:s', $max); // 2012-06-11 08:30:49
Run Code Online (Sandbox Code Playgroud)
PEM*_*PEM 25
做一个循环,将值转换为日期,并将最新的值存储在var中.
$mostRecent= 0;
foreach($dates as $date){
$curDate = strtotime($date);
if ($curDate > $mostRecent) {
$mostRecent = $curDate;
}
}
Run Code Online (Sandbox Code Playgroud)
类似的东西......你明白了如果你今天最想要的话:
$mostRecent= 0;
$now = time();
foreach($dates as $date){
$curDate = strtotime($date);
if ($curDate > $mostRecent && $curDate < $now) {
$mostRecent = $curDate;
}
}
Run Code Online (Sandbox Code Playgroud)
按日期对数组进行排序,然后获取数组的前值.
$dates = array(5) { /** omitted to keep code compact */ }
$dates = array_combine($dates, array_map('strtotime', $dates));
arsort($dates);
echo $dates[0];
Run Code Online (Sandbox Code Playgroud)
$dates = [
"2012-06-11 08:30:49"
,"2012-06-07 08:03:54"
,"2012-05-26 23:04:04"
,"2012-05-27 08:30:00"
,"2012-06-08 08:30:55"
];
echo date("Y-m-d g:i:s",max(array_map('strtotime',$dates)));
Run Code Online (Sandbox Code Playgroud)