dsgk40568 2012-10-29 20:53
浏览 46
已采纳

如何在下拉列表中围绕php数组值包装optgroup标签

I have an array called $selection that contains ascending time values from 09:00 to 18:00 in 15 minute intervals.

eg: $selection = array(09:00, 09:15, 09:30, 09:45, 10:00, 10:15, 10:30);

Some intervals could be missing, because this array is generated from some prior code which determines which times are available from google calendar (amongst other things). 09:00 isn't always the start time, sometimes the entire morning could be booked out.

I am using this array to create a drop down list.

foreach($selection as $slot) {
  if ( $slot == $selection[0] ) {
    print '<option value="'.$slot.'" selected="selected">'.date('H:i',  strtotime($slot)).'</option>';
  } else {
    print '<option value="'.$slot.'">'.date('H:i', strtotime($slot)).'</option>';
  } // end else
}

Problem

I am trying to add

<optgroup label="Morning"> .. </optgroup>

and

<optgroup label="Afternoon"> .. </optgroup>

Not sure how to do this. I have come to the conclusion that I need a while loop. Perhaps even adding extra information into the array before running the foreach loop.. not sure!

Would appreciate any help

  • 写回答

2条回答 默认 最新

  • dsxrq28228 2012-10-29 21:45
    关注

    For sorted array:

    $interval = '';
    $prev_interval = '';
    
    foreach($selection as $slot) 
    {
        // Check if selected option
    
        $sel = ( $slot == $selection[0] ) ? ' selected = "selected" ' : '';
    
        // Set optgroup interval; 
        // for HH:MM we can use basic string alphabet comaparsion
    
        if ($slot > '22:00')
        {
           $interval = 'Night';
        } 
        else if ($slot > '18:00')
        {
           $interval = 'Evening';
        }
       ...
    
        // check if interval has changed
    
        if ($prev_interval != $interval)
        {  
           // check if previous intrval was set
    
           if ($prev_interval!='') {  echo "</optgroup>" };
    
           printf('<optgroup label="%s">',$interval); 
        } 
    
        printf('<option value="%s"%s>%s</option>',$slot,$sel,date('H:i',  strtotime($slot)))  ;
    
        $prev_interval = $interval;
    }
    
    // last close element
    
    if ($interval!='') { echo '</optgroup>'; } 
    

    If the array can't be sorted before, simply store to 2D array while loop and print after.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置