dongpochi9741 2013-11-23 17:23 采纳率: 100%
浏览 52
已采纳

PHP重置while()循环

I am using the following which basically prints a dropdown box showing all hours with 30 minute increments:

$start = '12:00AM';
$end = '11:59PM';
$interval = '+30 minutes';

$start_str = strtotime($start);
$end_str = strtotime($end);
$now_str = $start_str;

echo '<select name="doors_open">';

while($now_str <= $end_str){
    echo '<option value="' . date('h:i A', $now_str) . '">' . date('h:i A', $now_str) . '</option>';
    $now_str = strtotime($interval, $now_str);
}

echo '</select>';

BUT, i want to do it twice for another field further down the page... question is, how do I reset the loop?

Here's what I've tried but doesn't work:

echo '<select name="event_start">';

reset($now_str);
reset($end_str);
while($now_str <= $end_str){
    echo '<option value="' . date('h:i A', $now_str) . '">' . date('h:i A', $now_str) . '</option>';
    $now_str = strtotime($interval, $now_str);
}

echo '</select>';
  • 写回答

2条回答 默认 最新

  • drzyeetvt41077335 2013-11-23 17:27
    关注

    reset() resets the internal cursor of an array. That's a totally different thing than you want to achieve.

    You can of course simply duplicate the code, but this neither good code design nor DRY.

    The best you can do is to put the whole HTML generation into a helper function:

    function genSelect($selectName, $start, $end, $interval) {
      $str = "<select name='$selectName'>";
    
      $start_str = strtotime($start);
      $end_str = strtotime($end);
      $now_str = $start_str;
    
    
      while($now_str <= $end_str){
        $str .= '<option value="' . date('h:i A', $now_str) . '">' . date('h:i A', $now_str) . '</option>';
        $now_str = strtotime($interval, $now_str);
      }
    
      $str .= '</select>';
      return $str;
    }
    

    Then, you can call it as often as you want:

    echo genSelect('doors_open', '12:00AM', '11:59PM', '+30 minutes');
    

    You may also consider caching the result:

    $doorsOpenHtml = genSelect('doors_open', '12:00AM', '11:59PM', '+30 minutes');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c