在php </select>的<select>输入字段中标识所选值

时间:2014-01-23 00:53:34

标签: php

我正在使用更新页面,其中我使用<select>输入字段,我想从我的数据库中获取days并使其成为输入字段的selected值。它工作正常,但我的问题是当控制中的那些选定日期被设置为selected时,其他日子正在重复。
例如:

<select name="day[]">
    <option value=""></option>
    <option>Monday</option>
    <option>Tuesday</option>
    <option>Wednesday</option>
    <option>Thursday</option>
    <option>Friday</option>
    <option>Saturday</option>
    <option>Sunday</option>
</select>       

my_days = array('Monday','Wednesday','Friday');

因此,在此示例中,MondayWednesdayFriday将被选中而不会重复  这是我的代码:

   <?php
        $day = $rows_load['day'];
        $days = explode(',', $day);
        $n = count($days);
         $the_days = array(
             'Monday' => 'Monday',
             'Tuesday' => 'Tuesday',
             'Wednesday' => 'Wednesday',
             'Thursday' => 'Thursday',
             'Friday' => 'Friday',
             'Saturday' => 'Saturday',
             'Sunday' => 'Sunday',
            );
     ?>

    <select data-placeholder="SELECT A DAY" multiple class="chosen-select chzn-select" tabindex="8" name="day[]" id="day" style="width:95%; " align="left" required>
        <option value=""></option>
        <?php 
        for($x = 0;$x < $n; $x ++){ 
         echo "<option selected>".$the_days[ $days[ $x ] ] ."</option>";
        }
        ?>

        <option>Monday</option>
        <option>Tuesday</option>
        <option>Wednesday</option>
        <option>Thursday</option>
        <option>Friday</option>
        <option>Saturday</option>
        <option>Sunday</option>
    </select>    

参见图片参考链接

http://postimg.org/image/pqk2sn4kn/ - 这是上面代码的输出。

1 个答案:

答案 0 :(得分:0)

foreach ($the_days as $day_name) {
    if (in_array($day_name, $days)) {
        echo '<option selected>';
    } else {
        echo '<option>';
    }
    echo $day_name . '</option>';
}

DEMO