我正在尝试使用一个表单,用户可以选择具有特定值的多个复选框。然后,服务器端将获取用户输入并使用逗号分隔列表回显句子。
<input type="checkbox" name="apples" value="apples"/>
<input type="checkbox" name="oranges" value="oranges"/>
<input type="checkbox" name="bananas" value="bananas"/>
<input type="checkbox" name="pears" value="pears"/>
输出将是“我喜欢吃苹果”。 或者“我喜欢吃苹果和香蕉。” 或者“我喜欢吃苹果,香蕉和梨子。” 如果没有选择框,则不显示任何内容。
<?php $apples = (isset($_POST['apples']) ? $_POST['apples'] : ''); ?>
<?php $oranges = (isset($_POST['oranges']) ? $_POST['oranges'] : ''); ?>
<?php $bananas = (isset($_POST['bananas']) ? $_POST['bananas'] : ''); ?>
<?php $pears = (isset($_POST['pears']) ? $_POST['pears'] : ''); ?>
谢谢!
答案 0 :(得分:1)
我会使用相同的名称作为复选框(作为数组):
<input type="checkbox" name="fruit[]" value="apples"/>
<input type="checkbox" name="fruit[]" value="oranges"/>
<input type="checkbox" name="fruit[]" value="bananas"/>
<input type="checkbox" name="fruit[]" value="pears"/>
然后使用以下内容:
$fruit = $_POST['fruit'];
if (!isset($fruit[2]))
{
echo implode(' and ', $fruit);
}
else
{
array_push($fruit, 'and ' . array_pop($fruit));
echo implode(', ', $fruit);
}
答案 1 :(得分:0)
怎么样:
<?php
$fruit = array();
if(isset($_POST['apples']) $fruit[] = 'apples';
if(isset($_POST['oranges']) $fruit[] = 'oranges';
if(isset($_POST['bananas']) $fruit[] = 'bananas';
if(isset($_POST['pears']) $fruit[] = 'pears';
if( count( $fruit ) <= 0 ) {
} else if( count( $fruit ) == 1 ) {
echo "I like to eat " . $fruit[0] . ".\n";
} else {
$lastFruit = array_pop( $fruit );
echo "I like to eat " . implode( ",", $fruit ) . " and $lastFruit.\n";
}
?>