我有这段代码:
$genders = array('Male', 'Female');
foreach ( $genders as $gender ) {
echo '<option' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
echo $gender;
echo '</option>';
}
并且该代码生成如下HTML代码:
<option selected>Male</option>
<option>Female</option>
现在,我想在每个选项上添加一个值,以便输出如下:
<option selected value='M'>Male</option>
<option value='F'>Female</option>
我认为通过将数组更改为关联数组可以解决这个问题:
$genders = array('M'=>'Male', 'F'=>'Female');
但如何获取数组的索引,以便它可以用作选项标记的值?
答案 0 :(得分:1)
您只需将输出脚本更改为以下内容:
$genders = array('M' => 'Male', 'F' => 'Female');
foreach ( $genders as $gender => $description ) {
echo '<option value='.$gender.' ' . ( $rowMyBiodata['Gender'] == $description ? ' selected' : '' ) . '>';
echo $description;
echo '</option>';
}
注意foreach参数的新用法有$ key =&gt; $ value对,然后在输出中使用它
答案 1 :(得分:1)
像这样:
$genders = array('M' => 'Male', 'F' => 'Female');
foreach ($genders as $key => $value) {
echo '<option' . ($rowMyBiodata['Gender'] == $value ? ' selected' : '' ) . ' value="' . $key . '">';
echo $value;
echo '</option>';
}
答案 2 :(得分:0)
使用如下,
foreach ( $genders as $key=>$gender ) {
echo '<option value='.$key.' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
echo $gender;
echo '</option>';
}