【问题标题】:Php checkbox POST arrayphp 复选框 POST 数组
【发布时间】:2015-09-15 16:55:39
【问题描述】:

我有一个带有复选框的 html 联系表单。当我去获取 $_POST 数据时,我看到的复选框字段都是 ARRAY。

这是 HTML 表单中的复选框 sn-p

  <div class="col-md-3">
    <div class="checkbox">
      <label>
        <input type="checkbox" name="services[]" value="check 1">Type 1
      </label>
    </div>
  </div>

  <div class="col-md-3">
    <div class="checkbox">
      <label>
        <input type="checkbox" name="services[]" value="check 2 ">Type 2
      </label>
    </div>
  </div>

  <div class="col-md-3">
    <div class="checkbox">
      <label>
        <input type="checkbox" name="services[]" value="check 3">Type 3
      </label>
    </div>
  </div>

  <div class="col-md-3">
    <div class="checkbox">
      <label>
        <input type="checkbox" name="services[]" value="check 4">Type 4
      </label>
    </div>
  </div>

这是我的 PHP 处理文件

$email = $_POST['email'];

if ( is_array ( $_POST['services'] ) ) {
    $services = $_POST['services'];
}

echo 'email is: ' . $email . ' services :' . $services;

电子邮件工作正常,因为它只是来自一个输入字段的 POST 数据。但是如何将数组保存到变量中,以便它执行类似

的操作
$services = "check 1, check 2, check 3";

【问题讨论】:

  • $_POST['services'] 是一个数组。因此,您可以调用每个数组元素的值,例如 $_POST['services'][0]$_POST['services'][1] 等。最简单的方法是使用 foreach 循环。

标签: php arrays checkbox


【解决方案1】:

我猜您只是想将该数组放入您的电子邮件中。在这种情况下,PHP 将只使用单词 Array 来让您知道它是实际的数组,而不是字符串。

要获得逗号分隔的列表,您应该在 $services 上使用 implode() 函数(不要忘记先过滤它!)。

$commaList = implode(', ', $services);

【讨论】:

    【解决方案2】:

    您应该在 PHP 中使用implode() 函数。

    $variable = implode(', ', $services);
    

    您也可以使用 foreach 循环。

    $variable = '';
    foreach($services as $key => $value){
        $variable .= $value . ', ';
    }
    
    rtrim($variable, ', ');
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2012-10-16
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多