【问题标题】:Add Selected 'Attribute' to Select Box Based on PHP Time添加选定的“属性”以根据 PHP 时间选择框
【发布时间】:2009-10-21 20:07:06
【问题描述】:

我目前正在使用以下 PHP 代码生成具有不同时间的选择框:

 <?
 for ($x = 28; $x < 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>";
   }
 }
?>

所有时间间隔为 15 分钟: 12:00:00 12:15:00 12:30:00 12:45:00 13:00:00 //等等...

我想知道的是:如何给定当前时间,使最接近的时间成为“选定”时间。

例如,如果当前 PHP 时间是:12:32:14,我希望它选择“12:45 pm”。

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: php date time scripting


    【解决方案1】:
    <?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);
    }
    ?>
    

    【讨论】:

      【解决方案2】:

      这是一个开始。您需要稍微扩展一下条件,这样当表达式评估为负数时,您就不会继续输出“已选择”。

       <?
       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>";
       }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-19
        • 2012-07-02
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2012-09-10
        • 2021-03-27
        • 1970-01-01
        相关资源
        最近更新 更多