2013-08-31 123 views
0
<select name="year"><?=options(date('Y'),1900)?></select> 
<select name="month"><?php echo date('m');?><?=options(1,12,'callback_month')?></select> 
<select name="day"><?php echo date('d');?><?=options(1,31)?></select> 

PHP創建選擇選項,並獲得當前值的月份和日期

function options($from,$to,$callback=false) 
{ 
    $reverse=false; 

    if($from>$to) 
    { 
     $tmp=$from; 
     $from=$to; 
     $to=$tmp; 

     $reverse=true; 
    } 

    $return_string=array(); 
    for($i=$from;$i<=$to;$i++) 
    { 
     $return_string[]='<option value="'.$i.'">'.($callback?$callback($i):$i).'</option>'; 
    } 
    if($reverse) 
    { 
     $return_string=array_reverse($return_string); 
    } 

    return join('',$return_string); 
} 

function callback_month($month) 
{ 
    return date('m',mktime(0,0,0,$month,1)); 
} 

我應該做出什麼來得到當前的月份和日期在相應的下拉列表中的初始值,因爲它是這樣與幾年(2013)。

+1

可以在另一個參數傳遞給選項()函數,這是本年度/當月。在將下拉選項連接起來的函數中,檢查循環中的當前值是否與paased參數相同,在選項 – rakeshjain

+1

中添加selected ='selected'您不應該調用數組'$ return_string'。爲了便於閱讀,請將其稱爲'$ options_array'或其他內容。 –

回答

2

嘗試像以下:

增加了新的PARAM typeoptions()功能

<select name="year"><?=options('year' ,date('Y'),1900)?></select> 
<select name="month"><?php echo date('m');?><?=options('month', 1,12,'callback_month')?></select> 
<select name="day"><?php echo date('d');?><?=options('day', 1,31)?></select> 

<?php 

function options($type, $from,$to,$callback=false) 
{ 
    $reverse=false; 

    switch ($type) 
    { 
     case "year": 
      $current = date('Y'); 
      break; 
     case "month": 
      $current = date('m'); 
      break; 
     case "day": 
      $current = date('d'); 
      break; 
    } 

    if($from>$to) 
    { 
     $tmp=$from; 
     $from=$to; 
     $to=$tmp; 

     $reverse=true; 
    } 

    $return_string=array(); 
    for($i=$from;$i<=$to;$i++) 
    { 
     $selected = ($i == $current ? " selected" : ""); 
     $return_string[]='<option value="'.$i.'" '.$selected.'>'.($callback?$callback($i):$i).'</option>'; 
    } 
    if($reverse) 
    { 
     $return_string=array_reverse($return_string); 
    } 

    return join('',$return_string); 
} 

function callback_month($month) 
{ 
    return date('m',mktime(0,0,0,$month,1)); 
} 

?> 
1

只是retreive當前日期FIRST和使用一個for循環,每年

1

減去使用selected屬性:

例如

<select> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="vw">VW</option> 
    <option value="audi" selected>Audi</option> 
</select> 

小提琴這裏:http://jsfiddle.net/dd3FU/

只要把一個if statement內。

享受!

+0

joespina,你的意思是:'if option value == date(m)then attr selected = true?' – bonaca

+0

取決於你的朋友。如果它取決於我,我會讓它像是如果(日期==日期現在){回聲選擇}其他{回聲其他};不管什麼讓你更舒服會更好。這裏的關鍵元素是'selected'屬性。 –

相關問題