2016-07-04 95 views
0

我有給了我一個「跳」菜單中把一個查詢在當前的URL,如日期= 2016-07設置選擇列表中的默認值

<?php 
    $date = explode('-', $_GET['date']); 
    $year = $date[0]; 
    $month = $date[1]; 
?> 

<form> 
<select name="date" onchange="this.form.submit()"> 
<?php 
    for ($i = 0; $i <= 18; ++$i) { 
    $time = strtotime(sprintf('+%d months', $i)); 
    $value = date('Y-m', $time); 
    $label = date('F Y', $time); 
    printf('<option value="%s">%s</option>', $value, $label); 
    } 
    ?> 
</select> 
</form> 

以下?一旦頁面跳過,我想顯示新的日期作爲默認值。我以爲你通過給選擇列表賦予一個「value」屬性來做到這一點,但那並不奏效。進一步閱讀,你需要添加「選擇」的選項之一。

如果與URL中的日期查詢匹配,我將如何將「selected」添加到其中一個選項中?

+0

測試'$ _GET [ '日期'] == $ value'如果是添加'選擇= 「選擇」' – RiggsFolly

回答

1
<?php 
    $date = explode('-', $_GET['date']); 
    $year = $date[0]; 
    $month = $date[1]; 
?> 

<form> 
<select name="date" onchange="this.form.submit()"> 
<?php 
    for ($i = 0; $i <= 18; ++$i) { 
    $time = strtotime(sprintf('+%d months', $i)); 
    $value = date('Y-m', $time); 
    $label = date('F Y', $time); 
    if(strcmp($value,$_GET['date']) == 0) 
     //If 0, $value and $_GET['date'] are the same: The option is selected 
     printf('<option value="%s" selected>%s</option>', $value, $label); 
    else 
     printf('<option value="%s">%s</option>', $value, $label); 
    } 
    ?> 
</select> 
</form> 
+1

完美,謝謝! – Collins

1
$selected = ($value == $_GET['date']) ? 'selected' : ''; 
printf('<option value="%s" %s>%s</option>', $value, $selected, $label);