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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料