我有6个美国州(夏威夷,俄亥俄州,路易斯安那州,弗吉尼亚州,田纳西州和德克萨斯州)。我有另外一组美国3个国家,这些国家是从美国上述6个州(俄亥俄州,弗吉尼亚州,德克萨斯州)中选出的。
如何让PHP生成总共6个状态的复选框列表,但选中状态是否已选中?我的代码列在下面,似乎无法让它运行:
<!DOCTYPE>
<html>
<head>
<style>
#locationsBox {
border: 2px solid #ccc;
width: 250px;
height: 100px;
overflow-y: scroll;
}
</style>
</head>
<body>
<div id="locationsBox">
<form name="location_checkboxes">
<?
$locations = array("Hawaii","Ohio","Louisiana","Virginia","Tennessee","Texas");
$selected_locations = array("Ohio","Virginia","Texas");
for($i = 0; $i < sizeOf($locations); $i++) {
if (false != $key = array_search($selected_locations[$i],$locations) {
echo '<input type="checkbox" checked="yes" value="'.$locations[$key].'" />' . $locations[$key] . '<br />';
} else {
echo '<input type="checkbox" value="'.$locations[$i].'" />' . $locations[$i] . '<br />';
}
}
?>
</form>
</div>
</body>
</html>
感谢您的任何建议!
答案 0 :(得分:1)
<?php
$locations = array("Hawaii","Ohio","Louisiana","Virginia","Tennessee","Texas");
$selected_locations = array("Ohio","Virginia","Texas");
foreach($locations as $l)
{
if(in_array($l,$selected_locations))
{
echo '<input type="checkbox" name="location[]" checked="checked" value="'.$l.'" />' . $l . '<br />';
echo "<br />";
}
else
{
echo '<input type="checkbox" name="location[]" value="'.$l.'" />' . $l . '<br />';
}
}
?>