doutang1946 2015-02-06 13:52
浏览 19
已采纳

如何使用PHP数组中的值在HTML选择控件中设置多个默认值?

This is sort of an extension of the problem solved here: Set default value for HTML select control in PHP however I would like to fill in Multiple values that match, with the values to fill in stored in an additional array:

This is my code so far:

<select name="genres[]" id="genres_edit" multiple>
<?php
$genrelist = array(  
'Action',  
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
for($i = 0;$i < count($genrelist);$i++) {
    echo "<option value=\"$genrelist[$i]\"";
    for ($g = 0; $g < count($genre);$g++) {
        if ($genrelist[$i] == $genre[$g]) {
            echo "selected=\"selected\"";
        }
    echo ">$genrelist[$i]</option>";
    }
}
?>
</select>

$genrelist is the array of all possible genres that will be used to fill up the select control, and the array of actual genres is stored in $genre.

Basically I want it to highlight the values in the selectbox that match any of the values in the $genre array.

i.e. if the genres stored in $genres are: Adventure, Cooking, Western, then those 3 values will be highlighted in the select box, out of the 6 available genres in the box.

  • 写回答

3条回答 默认 最新

  • dsjk3214 2015-02-06 14:03
    关注

    Here's how I'd do it ...

    $genres = array(
        'Action',
        'Western'
        );
    
    $genrelist = array(
        'Action',  
        'Adventure',
        'Comedy',
        'Cooking',
        'War',
        'Western');
    
    foreach ($genrelist as $k=>$v) {
        $sel = (array_search($v,$genres) !== false) ? ' selected' : '';
        echo '<option value="'. $k .'"'. $sel .'>'. $v .'</option>';
    }
    

    Here's the sandbox ... http://sandbox.onlinephpfunctions.com/code/e4f2ca28e0fd43513b694f5669329cc1db328598

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

报告相同问题?

悬赏问题

  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离