1

如果值与函数生成的值匹配,如何从下拉列表中选择值?例如,如果$match value is 08:00条件应从下拉列表中选择值,则无法选择值?

PHP 函数

function create_time_range($start, $end, $interval = '15 mins', $format = '12') {
$startTime = strtotime($start);
$endTime   = strtotime($end);
$returnTimeFormat = ($format == '12')?'H:i':'H:i';

$current   = time();
$addTime   = strtotime('+'.$interval, $current);
$diff      = $addTime - $current;

$times = array();
while ($startTime < $endTime) {
    $times[] = date($returnTimeFormat, $startTime);
    $startTime += $diff;
}
$times[] = date($returnTimeFormat, $startTime);
return $times;
}

$times= create_time_range('00:00', '23:45', '15 mins');

$match = '08:00';

html

<select name="time_picker">
<option value="">Select Time</option>
<?php foreach($times as $key=>$val){ ?>

    <?php
    if (in_array($match, $times))
    {
        $selected = 'selected';
    }
    ?>

  <option <?php echo $selected ?> value="<?php echo $val; ?>"><?php echo $val; ?></option>
<?php } ?>
</select>
4

1 回答 1

2

将您的 html 部分更新为以下内容

<select name="time_picker">
<option value="">Select Time</option>
<?php foreach($times as $key=>$val){ 
  $selected = $match===$val ? 'selected' : '';
?>
  <option <?php echo $selected ?> value="<?php echo $val; ?>"><?php echo $val; ?></option>
<?php } ?>
</select>
于 2020-10-21T14:01:39.683 回答