2016-02-12 262 views
1

选择下拉有一个简单的if语句为默认从下拉正确的日期?因此,例如,如果日期是02/11/16然后它会默认选择 01/28/16 基本上我要求的是一个声明,如果默认选择的下拉该日期内从日期范围

<?php 
        date_default_timezone_set('US/Eastern'); 
        $currenttime = date('d:m:y:h:i:s A'); 
        list($day,$month,$year) = split(':',$currenttime); 
        $currentdate = "$month/$day/$year"; 
?> 


<form> 
<select> 
<option>01/14/16</option> 
<option>01/28/16</option> 
<option>02/14/16</option> 
///the list goes on for ages so i saved time and cropped out the rest of the dates. 
</select> 
</form> 
+0

你将如何决定它是在计费周期? –

+2

你为什么不只是做'$的currentdate =日期( “M/d/Y”)',而不是分裂的时间? – Barmar

+1

@Sougata看起来帐单期限是菜单中日期之间的范围。 – Barmar

回答

1

把所有的日期在一个数组中,并循环它们。然后您可以测试它们并确定当前日期是否在结算期间。

$dates = array('16-01-14', 
       '16-01-28', 
       '16-02-14', 
       ...); 
$currentdate = date('y-m-d'); 

?> 
<form> 
<select> 
<?php 
foreach ($date as $i => $d) { 
    if ($currentdate >= $d && ($i == count($dates)-1 || $currentdate < $dates[$i+1])) { 
     $selected = "selected"; 
    } else { 
     $selected = ""; 
    } 
    list($year, $month, $day) = explode('-', $d); 
    echo "<option $selected>$month/$day/$year</option>"; 
} 
?> 
</select> 
</form> 

我改变的$currentdate的格式y-m-d,使他们可以按照字符串进行比较,看是否日期是在一个范围内。

由于它遍历日期列表,它测试的当前日期是否是数组中的日期和未来日期间(或它的阵列中的最后日期)。如果是,它增加了selected属性为<option>

+0

@barmar谢谢你的回应是否有可能问这是如何工作的?如果不是它的罚款,我仍然会将这个问题标记为回答,只是想知道你是否可以更具体;我不明白的是foreach函数? – Johnny

+1

我已经给答案增加了一些解释。 – Barmar

+1

让我知道它是否仍然不清楚它是如何工作的。 – Barmar