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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀