我从PHP数组生成一个HTML Select菜单$ times,如下所示:
Array ( [9:00am] => 9:00am [9:30am] => 9:30am [9:45am] => 9:45am [10:00am] => 10:00am [10:30am] => 10:30am [10:45am] => 10:45am [11:00am] => 11:00am [11:30am] => 11:30am [11:45am] => 11:45am [12:00pm] => 12:00pm [12:30pm] => 12:30pm [12:45pm] => 12:45pm [1:00pm] => 1:00pm [1:30pm] => 1:30pm [1:45pm] => 1:45pm [2:00pm] => 2:00pm [2:30pm] => 2:30pm [2:45pm] => 2:45pm [3:00pm] => 3:00pm [3:30pm] => 3:30pm [3:45pm] => 3:45pm [4:00pm] => 4:00pm [4:30pm] => 4:30pm [4:45pm] => 4:45pm [5:00pm] => 5:00pm [5:30pm] => 5:30pm [5:45pm] => 5:45pm [6:00pm] => 6:00pm [-] => - )
我按如下方式构建选择菜单,比较每个选项以查看它是否与数据库记录中的值匹配,以便可以标记为已选择:
<?php
$ output =&#39;&#39 ;;
foreach($times as $time) {
$time = htmlspecialchars($time);
if ($time == $record->getField('HotPhotoTime')) {
$output = "<option value='".$time."' selected='selected' >$time</option>";
} else {
$output = "<option value='".$time."'>$time</option>";
}
echo $output;
} ?&GT;
我现在需要更新它以处理数据库记录中的值的情况:
$time == $record->getField('HotPhotoTime')
实际上并不是选择菜单中的选项之一,例如&#34; 5:15 pm&#34;。这当前不会显示为已选中,但任何不匹配的值都应包含在选择菜单中并标记为已选中。
答案 0 :(得分:0)
这是一个符合您需求的示例。希望这会有所帮助。
<?php
$times = array(
'01:00' => '01:00',
'02:00' => '02:00',
'03:00' => '03:00',
'04:00' => '04:00',
'05:00' => '05:00',
'06:00' => '06:00',
'07:00' => '07:00',
'08:00' => '08:00',
'09:00' => '09:00'
);
$addThisTime = '04:15';
if(!in_array($addThisTime,$times))
{
$times[''.$addThisTime.''] = $addThisTime;
ksort($times);
}
$html = '<select name="yourSelect" id="yourSelectID">';
foreach($times as $v)
{
$html .= '<option value="'.$v.'" '.(strcmp($v,$addThisTime)==0 ? 'selected' : '').'>'.$v.'</option>';
}
$html .= '</select>';
echo $html;