0

我有这个代码:

$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');

但是如何获取数组的索引以便它可以用作选项标签上的值?

4

3 回答 3

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 => $value 对,然后在输出中使用它

于 2012-11-16T04:01:26.193 回答
1

像这样:

$genders = array('M' => 'Male', 'F' => 'Female');

foreach ($genders as $key => $value) {
    echo '<option' . ($rowMyBiodata['Gender'] == $value ? ' selected' : '' ) . ' value="' . $key . '">';
    echo $value;
    echo '</option>';
}
于 2012-11-16T04:01:35.947 回答
0

使用如下,

foreach ( $genders as $key=>$gender ) {
  echo '<option value='.$key.' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
  echo $gender;
  echo '</option>';

}

于 2012-11-16T04:05:21.343 回答