很抱歉,我目前在这一部分遇到了问题。我的日期格式是Y-m-d
$date1 = '2016-03-1';
$date2 = '2016-07-1';
$date3 = '2016-10-1';
$date4 = '2016-12-1';如果今天是2016-8-12,那么它应该落在$date3,因为它是下一段时间。我尝试使用if条件,但它只适用于第一个条件。你能在这方面给我一些启发吗?
我的代码有点像这样
$today = date("2016-07-29");
if(strtotime($date1) < strtotime($today)){
$next_accrual_date = $date1;
$date_condition = 'condition 1';
}else
if(strtotime($date2) < strtotime($today)){
$next_accrual_date = $date2;
$date_condition = 'condition 2';
}else
if(strtotime($date3) < strtotime($today)){
$next_accrual_date = $date3;
$date_condition = 'condition 3';
}else
if(strtotime($date4) < strtotime($today)){
$next_accrual_date = $date4;
$date_condition = 'condition 4';
}
echo $next_accrual_date." falls to ".$date_condition;发布于 2016-08-12 16:02:00
实现此目的的一种方法是
<?php
$dates = array();
$dates[] = '2016-03-1';
$dates[] = '2016-07-1';
$dates[] = '2016-10-1';
$dates[] = '2016-12-1';
usort($dates, "cmp");
function cmp($a, $b){
return strcmp($a, $b);
}
foreach($dates as $date){
if($date > "2016-08-12"){
echo $date;
break;
}
}
//print_r($dates);
?>这将给出输出:
2016-10-1发布于 2016-08-12 16:02:50
$today = strtotime(date('Y-m-d'));
$currentYear = date('Y');
$dates = ['q1' => strtotime($currentYear.'-03-1'),
'q2' => strtotime($currentYear.'-07-1'),
'q3' => strtotime($currentYear.'-10-1'),
'q4' => strtotime($currentYear.'-12-1')];
foreach ($dates as $qName => $qDate) {
if ($qDate > $today) {
return "$qDate falls to $qName";
}
}发布于 2016-08-12 16:07:58
只需将您的比较从<更改为>:
$today = date("2016-07-29");
if(strtotime($date1) > strtotime($today)){
$next_accrual_date = $date1;
$date_condition = 'condition 1';
}else ...
echo $next_accrual_date." falls to ".$date_condition;它会起作用的。目前,您查看今天是否大于第一季度的日期,然后打破if。但是在“2016-03-1”之后的每个日期都会出现这种情况。这就是为什么你总是得到条件1的原因。
https://stackoverflow.com/questions/38912654
复制相似问题