问题描述
我有一个数组使用以下code创建的阵列。我试图通过得到这个循环和填充的下拉列表。
I have an array of an arrays created using the following code. I'm trying to get this to loop through and populate a dropdown list.
$names = $db->fetchAll("select `name` from `classes`");
这是什么是存储在$名称变量。
This is what is stored in the $names variable.
阵列([0] =>阵列([名称] =>网页设计)[1] =>阵列([名称] =>
艺术史)[2] =>阵列([名称] =>健身房)[3] =>阵列([名称] =>
英文)[4] =>阵列([名称] =>生物学)[5] =>阵列([名称] =>
三维动画)[6] =>阵列([名称] =>技术光盘)[7] =>阵列(
[名] =>数学)[8] =>阵列([名称] =>舞蹈)[9] =>阵列(
[名] =>视频制作)[10] =>阵列([名称] =>首页EC)[11]
=>阵列([名称] =>政府)[12] =>阵列([名称] =>物理))
我有这样的下拉列表中创建和它的工作,但它是在阵列中的每个值手codeD。我想修改此所以它的循环'到阵列中的所有结果来创建下拉列表。
I have this dropdown list created and it work, but it is hand coded for each value in the array. I want to modify this so it 'loops' through all results in the array to create the dropdown.
<label for="per1"></label>
<select name="per1" id="per1">
<option selected="selected">Choose one</option>
<option value="<?php echo $names[0]['name'];?>"><?php echo $names[0]['name'];?></option>
<option value="<?php echo $names[1]['name'];?>"><?php echo $names[1]['name'];?></option>
<option value="<?php echo $names[2]['name'];?>"><?php echo $names[2]['name'];?></option>
<option value="<?php echo $names[3]['name'];?>"><?php echo $names[3]['name'];?></option>
<option value="<?php echo $names[4]['name'];?>"><?php echo $names[4]['name'];?></option>
<option value="<?php echo $names[5]['name'];?>"><?php echo $names[5]['name'];?></option>
<option value="<?php echo $names[6]['name'];?>"><?php echo $names[6]['name'];?></option>
<option value="<?php echo $names[7]['name'];?>"><?php echo $names[7]['name'];?></option>
<option value="<?php echo $names[8]['name'];?>"><?php echo $names[8]['name'];?></option>
<option value="<?php echo $names[9]['name'];?>"><?php echo $names[9]['name'];?></option>
<option value="<?php echo $names[10]['name'];?>"><?php echo $names[10]['name'];?></option>
<option value="<?php echo $names[11]['name'];?>"><?php echo $names[11]['name'];?></option>
<option value="<?php echo $names[12]['name'];?>"><?php echo $names[12]['name'];?></option>
</select>
有人可以帮助?
推荐答案
该解决方案适用于目前的PHP版本。
使用foreach的简单情况:
This solution works for current PHP versions.Simple case of using a foreach:
<select name="per1" id="per1">
<option selected="selected">Choose one</option>
<?php
foreach($names as $name) { ?>
<option value="<?= $name['name'] ?>"><?= $name['name'] ?></option>
<?php
} ?>
</select>
该解决方案适用于旧的PHP版本。
使用foreach的简单情况:
This solution works for older PHP versions.Simple case of using a foreach:
<select name="per1" id="per1">
<option selected="selected">Choose one</option>
<?php
foreach($names as $name) { ?>
<option value="<?php echo $name['name'] ?>"><?php echo $name['name'] ?></option>
<?php
} ?>
</select>
这篇关于PHP foreach循环来填充值的下拉列表,从一个数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!