【问题标题】:Display array from php using html form checkbox使用 html 表单复选框从 php 显示数组
【发布时间】:2018-12-12 22:53:46
【问题描述】:

我有一种如下图所示的复选框:

<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 代码的问题是它根本没有进入第一个。它只显示来自其他两个 if 的两个表(因为也不显示回显)。有什么办法可以解决这个问题吗?

【问题讨论】:

  • $values[$i] 从数组中提取单个值,它不能同时是“1”和“2”。
  • 但是当我同时检查它们时,它需要两个值。当我使用 for 循环时,这不应该给它两个值吗?
  • 另外,如果可能的话,你能给我一个解决方案吗?
  • 你只有一个值 per 遍历循环。添加echo "index:" . $i . " value:" + $values[$i] 以可视化此。

标签: php html forms web-services post


【解决方案1】:

你不应该为此需要一个循环。您只需为每个有问题的值签入$_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
    }
}

【讨论】:

  • 单词作为值的唯一问题是,如果该值被用作 db 调用的 id 以获取水果和/或蔬菜列表.....很难从原始示例中分辨出来尽管。如果使用数字if(in_array("1", $_POST['options']) &amp;&amp;in_array("2", $_POST['options'])) 可以用于回显
  • @JonP 是的,如果这些数字要用于其他用途,我们当然不希望将它们变成这样的词。但即使我们坚持使用数字,这个想法也是一样的。只需在数组中查找每个,无需循环。
  • 刚刚尝试了你给我的解决方案,它奏效了。谢谢。
猜你喜欢
  • 2012-10-16
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 2011-09-18
  • 2023-02-17
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多