我有一种复选框形式,如下所示:
<form method="POST" action="display.php">
<input type="checkbox" value="1" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="2" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
<button class="button" type="submit" value="display">DISPLAY</button>
</form>
我使用$_POST['options']
获得options[]
,并将数据数组保存在一个变量中。如果选中了水果复选框,我想显示水果阵列,如果选中了蔬菜复选框,则显示蔬菜阵列,如果两者都选中,则显示两者,并显示一条消息"水果和蔬菜都很健康"。这是我到目前为止的php代码,但它似乎没有像我希望的那样工作
<?php
$values = $_POST['options'];
$n = count($values);
for($i=0; $i < $n; $i++ )
{
if($values[$i] === "1" && $values[$i] == "2")
{
//iteration to display both tables
echo 'Fruits and Vegetables are healthy';
}
else if($values[$i] === "1")
{
//display fruits
}
else if( $values[$i] == "2")
{
//display vegetables
}
}
?>
我的php代码的问题是is根本没有进入第一个if。它只显示其他两个if中的两个表(因为echo也不显示(。有什么办法可以解决这个问题吗?
您不需要循环。您只需要为每个有问题的值签入$_POST['options']
。我建议使用您想要显示的文本作为复选框的值,这样您就不必从数字转换为单词。
<input type="checkbox" value="Fruits" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="Vegetables" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
然后,对于显示器,只输出水果/蔬菜阵列,这取决于这些值是否存在于$_POST['options']
中。
if (!empty($_POST['options'])) {
echo implode(' and ', $_POST['options']) . " are healthy";
if (in_array('Fruits', $_POST['options'])) {
// show the fruits
}
if (in_array('Vegetables', $_POST['options'])) {
// show the veg
}
}