【问题标题】:PHP form that echo's a comma separated list [closed]回显逗号分隔列表的PHP表单[关闭]
【发布时间】:2013-04-01 15:36:34
【问题描述】:

我正在尝试创建一个表单,用户可以选择多个具有特定值的复选框。然后,服务器端将接受用户输入并用逗号分隔列表回显一个句子。

<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'] : ''); ?>

谢谢!

【问题讨论】:

  • 你到底试过什么
  • 很好。祝你好运!
  • 听起来很像一个任务。

标签: php forms comma


【解决方案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);

}

【讨论】:

    【解决方案2】:

    怎么样:

    <?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";
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2020-06-08
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      相关资源
      最近更新 更多