循环到一个数组,用PHP构建一个select

时间:2018-04-20 17:57:45

标签: php arrays

我在PHP中使用了以下数组:

$countries = array(
    array('CTY_Code' => 'AF', 'CTY_en' => 'Afghanistan', 'CTY_fr' => 'Afghanistan'),
    array('CTY_Code' => 'AL', 'CTY_en' => 'Albania', 'CTY_fr' => 'Albanie')
);

如何循环使用这个选项:

<select>
    <option value='AF'>Afghanistan</option>
    <option value='AL'>Albania</option>
</select>

我尝试了什么:

<select>
<?
foreach($CTY_Code as $key => $CTY_en) {
    echo '<option value="'.$CTY_Code.'">'.$CTY_en.'</option>';
}
?>
</select>

感谢。

3 个答案:

答案 0 :(得分:0)

尝试:

foreach ($countries as $key => $value) {
   echo '<option value="'.$value['CTY_Code'].'">'.$value['CTY_en'].'</option>';
}

答案 1 :(得分:0)

你的阵列。

$countries = array(
    array('CTY_Code' => 'AF', 'CTY_en' => 'Afghanistan', 'CTY_fr' => 'Afghanistan'),
    array('CTY_Code' => 'AL', 'CTY_en' => 'Albania', 'CTY_fr' => 'Albanie')
);

这是您的代码

echo "<select><option>--select country--</option>";
foreach ($countries as $countrykey => $countryvalue) {
        echo "<option value=".$countryvalue['CTY_Code'].">".$countryvalue['CTY_en']."</option>";
}
echo "</select>";

另一种在html中使用php的方法

<select><option>--select option--</option>
<?php foreach ($countries as $countrykey => $countryvalue) { ?>
    <option value="<?=$countryvalue['CTY_Code'];?>"><?=$countryvalue['CTY_en'];?></option>
<?php } ?>
</select>

答案 2 :(得分:0)

试试这样:

$countries = array(
    array('CTY_Code' => 'AF', 'CTY_en' => 'Afghanistan', 'CTY_fr' => 'Afghanistan'),
    array('CTY_Code' => 'AL', 'CTY_en' => 'Albania', 'CTY_fr' => 'Albanie')
);
echo sprintf(
    "<select>%s\n</select>",
    implode("", array_map(function ($value) {
        return sprintf("\n\t<option value=\"%s\">%s</option>", $value['CTY_Code'], $value['CTY_en']);
    }, $countries))
);

Demo Php

那会给你:

<select>
    <option value="AF">Afghanistan</option>
    <option value="AL">Albania</option>
</select>