开发者

Add Selected 'Attribute' to Select Box Based on PHP Time

I am currently using the following PHP code generate a Select Box with different times:

 <?
 for ($x = 28; $x &开发者_运维百科lt; 81; $x++) {
  if ($x == 48) {
  print "<option selected='selected' value='" . date("H:i:s", mktime(0, $x * 15, 0, 0, 0)) . "'>" . date("g:i a", mktime(0, $x * 15, 0, 0, 0)) . "</option>"; 
  }
   else {
   print "<option value='" . date("H:i:s", mktime(0, $x * 15, 0, 0, 0)) . "'>" . date("g:i a", mktime(0, $x * 15, 0, 0, 0)) . "</option>";
   }
 }
?>

All the times are at 15 minute intervals: 12:00:00 12:15:00 12:30:00 12:45:00 13:00:00 //etc...

What I'd like to know is: How can I given the current time, make the closest time the "selected" time.

For example, if the current PHP time is: 12:32:14, I'd like it to select "12:45 pm."

Any ideas on how to do this?


<?php
$start = '7:00:00';
$end = '20:00:00';
$now = time();
$ts = strtotime($start);
$endTs = strtotime($end);
while ($ts <= $endTs)
{
    $selected = '';
    if ($ts - $now > 0 && $ts - $now <= 60*15)
        $selected = 'selected="selected"';
    $time = date('H:i:s', $ts);
    echo "<option $selected value='$time'>" . date("g:i a", $ts) . "</option>\n";
    $ts = strtotime('+15 minutes', $ts);
}
?>


This is a start. You'll want to expand the conditional a bit so you don't keep outputting "selected" when the expression evalutes to something negative.

 <?
 for ($x = 28; $x < 81; $x++) {
   $sel = '';
   //if the current time is within 15 minutes of the computed time, select this box.
   if ( (mktime(0, $x*15, 0, 0, 0) - time()) < (15*60) )  $sel = 'selected="selected"';
   print "<option $sel value='" . date("H:i:s", mktime(0, $x * 15, 0, 0, 0)) . "'>" . date("g:i a", mktime(0, $x * 15, 0, 0, 0)) . "</option>";
 }
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜