如何使用PHP在下拉列表中设置等于字符串的选定值

时间:2017-03-03 11:31:13

标签: php

Hiii Everyone,

我在drop_1_1 is 'sds';

中的价值

选项中的其他值是

drop1[0]=as
drop1[1]=sds
drop1[2]=aa
drop1[3]=sa

如果drop_1_1值与上述任何值匹配,drop1 [0],drop1 [2]等,则应选择

以下是我的代码

$string = '<select name="drop_select1" class="user">
        <option value=\''.$drop1[0].'\'  if($drop_1_1==$drop1[0]) echo "selected=selected"; >'.$drop1[0].'</option>
        <option value=\''.$drop1[1].'\' if($drop_1_1==$drop1[1]) echo "selected=selected";>'.$drop1[1].'</option>
        <option value=\''.$drop1[2].'\' if($drop_1_1==$drop1[2]) echo "selected=selected";>'.$drop1[2].'</option>
        <option value=\''.$drop1[3].'\' if($drop_1_1==$drop1[3]) echo "selected=selected";>'.$drop1[3].'</option></select>';

在上面的代码中,没有选择值。

任何人都可以帮我解决我做错的事吗?

由于

3 个答案:

答案 0 :(得分:1)

你可以这样试试,

$selected = 'selected';
$string = '<select name="drop_select1" class="user">
        <option value=\''.$drop1[0].'\'  '.($drop_1_1==$drop1[0] ? $selected : "" ).'>'.$drop1[0].'</option>
        <option value=\''.$drop1[1].'\' '.($drop_1_1==$drop1[1] ? $selected : "" ).'>'.$drop1[1].'</option>
        <option value=\''.$drop1[2].'\' '.($drop_1_1==$drop1[2] ? $selected : "" ).'>'.$drop1[2].'</option>
        <option value=\''.$drop1[3].'\' '.($drop_1_1==$drop1[3] ? $selected : "" ).'>'.$drop1[3].'</option></select>';

你有语法错误,试一试,这样可行。

答案 1 :(得分:1)

实现此类目标的最佳方式是:

echo '<select>';
foreach($drop1 as $key => $value)
{
    $selected = '';
    if( $key == 'some value' )
    { 
        $selected = 'selected="selected"';
    }

    echo '<option value="'.$key.'" '.$selected.'>'.$value.'</option>'
}
echo '</select>';

答案 2 :(得分:1)

你可以使用任何循环

$drops = ["as","sds","aa","sa"];
$drop_selected = "sds";
$string = "<select name='drop_select1' class='user'>";
foreach($drops as $drop){
    $selected = ($drop == $drop_selected) ? ' selected ' : '';
    $string .= "<option $selected value='$drop'>$drop</option>";
}
$string .= "</select>";
echo $string;

现场演示:https://eval.in/747051