在网站开发中,我们经常要读取数据库,然后根据数据来显示信息。比如,我们从数据库中读取了这样一个数组:
array(\'cuke\' => \'B\',
\'stomach\' => \"B\",
\'tripe\' => \'C\',
\'taro\' => \'S\',
\'giblets\' => \'E\',
\'abalone\' => \'F\');
此时我们要将这个数组的数据绑定到select下拉列表上,要实现的效果如下:
<select name=\"main_dish\">
<option value=\"cuke\">B</option>
<option value=\"stomach\">B</option>
<option value=\"tripe\">C</option>
<option value=\"taro\">S</option>
<option value=\"giblets\">E</option>
<option value=\"abalone\">F</option>
</select>
该如何实现呢?其实很简单,我们只需要循环遍历这个数组就行了,代码如下:
<?
$main_dishes = array(\'cuke\' => \'B\',
\'stomach\' => \"B\",
\'tripe\' => \'C\',
\'taro\' => \'S\',
\'giblets\' => \'E\',
\'abalone\' => \'F\');
print \'<select name=\"main_dish[]\" multiple=\"multiple\">\';
foreach ($main_dishes as $option => $label) {
print \'<option value=\"\' . htmlentities($option) . \'\"\';
print \'>\' . htmlentities($label) . \'</option>\';
print \"\\n\";
}
print \'</select>\';
?>
<##ads_in_article_manong##>
假如我们又从数据库或其他地方得到这样一个数组:
array(\'cuke\',\'abalone\');
现在我们要将上面的select下拉列表的option值为cuke何abalone的两项作为默认选中项,该如何实现呢?请看下面改进的代码:
<?
$main_dishes = array(\'cuke\' => \'B\',
\'stomach\' => \"B\",
\'tripe\' => \'C\',
\'taro\' => \'S\',
\'giblets\' => \'E\',
\'abalone\' => \'F\');
print \'<select name=\"main_dish[]\" multiple=\"multiple\">\';
$selected_options = array();
$defaults=array(\'cuke\',\'abalone\');
foreach ($defaults as $option) {
$selected_options[$option] = true;
}
foreach ($main_dishes as $option => $label) {
print \'<option value=\"\' . htmlentities($option) . \'\"\';
if ($selected_options[$option]) {
print \' selected=\"selected\"\';
}
print \'>\' . htmlentities($label) . \'</option>\';
print \"\\n\";
}
print \'</select>\';
?> 继续阅读与本文标签相同的文章
-
美女机器人刚上市就售罄,除了生孩子,其他什么都能干!
2026-05-14栏目: 教程
-
互联网之光大会的黑科技,总有一款惊艳你!
2026-05-14栏目: 教程
-
微信宣布一项新举措,关系到每一个用户,网友一致力挺:干得漂亮!
2026-05-14栏目: 教程
-
微软建议企业客户卸载KB4520062累积更新
2026-05-14栏目: 教程
-
他让我国芯片研究停滞13年,还骗走11亿研发资金,现状如何?
2026-05-14栏目: 教程
