如何在 PHP 中将多个 <input type="checkbox" /> 作为数组发布?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1978781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:31:56  来源:igfitidea点击:

How to post multiple <input type="checkbox" /> as array in PHP?

phphtml

提问by user198729

So that in PHP I can deal with them as :

这样我就可以在 PHP 中处理它们:

foreach($_POST['checkboxname'] as $i => $value)
...

回答by KramerC

Do something like this:

做这样的事情:

<input type="checkbox" name="checkboxArray[]" />

Note the [] in the name.

请注意名称中的 []。

回答by Sarfraz

Like this:

像这样:

<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />

Just append [] to their names.

只需将 [] 附加到他们的名字。

回答by JestaBlunt

If you use an array for the checkboxes, you should add a value option as identifier for the single checkboxes, because then the returned array changes from Array ( [0] => on, [1] => on) to Array ( [0] => value1, [1] => value5 ), which let you identify the checked checkboxes.

如果您使用数组作为复选框,您应该添加一个值选项作为单个复选框的标识符,因为这样返回的数组将从 Array ( [0] => on, [1] => on) 更改为 Array ( [0] ] => value1, [1] => value5 ),它可以让您识别选中的复选框。

回答by sakthi sudhan

<html>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script>
  $(document).ready(function(even){
      $("button").click(function(){
            var checkvalue = [];
            $.each($("input[name='1']:checked"), function(){            
                checkvalue.push($(this).val());
            });
            alert("checkvalue: " + checkvalue.join(", "));
        });
  });
 </script>
 <body>
  <input type="checkbox" name="1" value="1" > 1 <br/>
  <input type="checkbox" name="1"  value="2"> 2 <br/>
  <input type="checkbox" name="1"  value="3"> 3 <br/>
  <button type="button">Get Values</button>
 </body>
</html>

回答by farzad

for those HTML form elements that can send multiple values to server (like checkboxes, or multiple select boxes), you should use an array like name for your HTML element name. like this:

对于那些可以向服务器发送多个值的 HTML 表单元素(如复选框或多个选择框),您应该为 HTML 元素名称使用类似 name 的数组。像这样:

<input type="checkbox" name="checkboxname[]" />

also it is recommended that you use an enctype of "multipart/form-data" for your form element.

还建议您为表单元素使用“multipart/form-data”的加密类型。

<form enctype="multipart/form-data" action="target.php" method="post">

then in your PHP scripts you can access the multiple values data as an array, just like you wanted.

然后在你的 PHP 脚本中,你可以像你想要的那样访问多个值数据作为一个数组。