下面是我试图开始工作的代码,但我对数组和foreach
知之甚少。所以它无法正常工作
我需要使用数组的内容向浏览器显示dropdown
选择表单
我还需要选择项目,如果它是==到$ mycountry 最后,我想将美国和英国列为我名单的首位
任何人都可以告诉我如何做到这一点
<?PHP
$countries = array(
"217" => "Turkenistan",
"218" => "Turks and Caicos Islands",
"219" => "Tuvalu",
"220" => "Uganda",
"221" => "Ukraine",
"222" => "United Arab Emirates",
"223" => "United Kingdom (Great Britain)",
"224" => "United States");
$mycountry = 224;
?>
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" />
<?php
$countryCounter = 1;
$amtOfCountries = count($countries);
//foreach ($country as $id => $c) {
for( $_top=0; $_top < $amtOfCountries; $_top++ ){
if ($countryCounter == $amtOfCountries) {
echo "<option value=\"$countries[0]\" SELECTED>$countries[1]</option>";
} else {
echo "<option value=\"$countries[0]\">$countries[1]</option>";
$countryCounter++;
}
}
?>
</select>
答案 0 :(得分:5)
foreach ($countries as $key => $country) {
$selected = ""
if ($key == $mycountry) $selected = ' selected="selected" ';
print '<option value=' . $key . $selected . '>' . $country . '</option>';
}
基本上,对于数组中的每个元素,您将其分解为其键及其值(即$ countreis [key] = value)。一旦你了解阵列(并且它们可能非常令人困惑),它将使编码容易一百万次。
(出于某种原因,语法高亮/格式化在我的代码中无效...)
答案 1 :(得分:1)
我猜你正在寻找:
foreach($countries as $id => $country) {
echo '<option value="$id"' . ($mycountry==$id?'selected="selected"':'') . '>' . $country . '</option>';
}
至于确保美国和英国排在首位,请确保这两个位于您的阵列之上(这将是最简单的)。
答案 2 :(得分:-1)
您应该将美国和英国放在数组的顶部,然后使用类似的内容:
foreach($countries as $row => $value) {
echo "<option value=\"$row\"" + ($row == 'usa' ? 'SELECTED') + ">$value</option>";
}
你应该使用selected =“selected”而不是SELECTED