php 从复选框形式制作数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4516847/
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
Make array from checkbox form
提问by austin
My friend and I are making a website that compiles news stories based on your interests. Is there and easy way to take the checkbox data and make an array out of the selected checkboxes? Here is our form
我和我的朋友正在制作一个网站,根据您的兴趣编辑新闻故事。有没有简单的方法来获取复选框数据并从选定的复选框中创建一个数组?这是我们的表格
<form action="signup.php" method="POST">
Name: <input type="text" name="name" /> <br />
Username: <input type="text" name="username"> <br />
Password: <input type="password" name="pwd" /> <br />
Email: <input type="text" name="email" /> <br />
<p>By filling out this we will be able to find news articles that will interest you</p> <br />
Politics<input type="checkbox" name="interest[]" value="Politics" /> <br />
Entertainment<input type="checkbox" name="interest[]" value="Entertainment" /> <br />
Tech <input type="checkbox" name="interest[]" value="Tech" /> <br />
Health<input type="checkbox" name="interest[]" value="Health" /> <br />
Living<input type="checkbox" name="interest[]" value="Living" /> <br />
Travel <input type="checkbox" name="interest[]" value="Travel" /> <br />
World<input type="checkbox" name="interest[]" value="World" /> <br />
Leisure<input type="checkbox" name="interest[]" value="Leisure" /> <br />
Finance<input type="checkbox" name="interest[]" value="Finance" /> <br />
Celebrity Gossip<input type="checkbox" name="interest[]" value="Gossip" /> <br />
Movies<input type="checkbox" name="interest[]" value="Movies" /> <br />
Sports<input type="checkbox" name="interest[]" value="Sports" /> <br />
<input type="submit" value="Submit">
</form>
how would we make a php array using this data?
我们将如何使用这些数据创建一个 php 数组?
回答by The Scrum Meister
the HTML markup:
HTML 标记:
<form method="get">
<input type="checkbox" name="options[]" value="Politics"/> Politics<br/>
<input type="checkbox" name="options[]" value="Movies"/> Movies<br/>
<input type="checkbox" name="options[]" value="World "/> World<br/>
<input type="submit" value="Go!" />
</form>
and in the php code:
并在 php 代码中:
$checked = $_GET['options'];
for($i=0; $i < count($checked); $i++){
echo "Selected " . $checked[$i] . "<br/>";
}
回答by Oli
use this:
用这个:
<input type="checkbox" name="mydata[checkbox1]"> Option 1 (politics etc)
<input type="checkbox" name="mydata[checkbox2]"> Option 2
<input type="checkbox" name="mydata[checkbox3]"> Option 3
then access $_POST["mydata"] as an array
然后访问 $_POST["mydata"] 作为数组
回答by Sondre
Sorry, posted before I was done writing:(
抱歉,还没写完就发了:(
Just a few improvements to the suggestions already posted:
只是对已经发布的建议进行了一些改进:
Use labels for the form:
为表单使用标签:
<label for="check_politics">Politics</label>
<input type="checkbox" name="intrests[]" id="check_politics" value="Politics"/>
Using labels to enhance a form is brilliant in my opinion:) Set their display to block if you want them to get linebreaks.
在我看来,使用标签来增强表单非常棒:) 如果您希望它们获得换行符,请将它们的显示设置为阻止。
And use foreach to loop through it on the serverside:
并使用 foreach 在服务器端循环遍历它:
$intrests = $_POST['intrests'];
foreach($intrests as $intrest) {
echo $intrest . " is my intrest";
}
回答by amypellegrini
The best way I found to do this (at least for me) was to convert the checkbox values into an array to manipulate it the way I wanted with implode and explode:
我发现这样做的最好方法(至少对我而言)是将复选框值转换为数组,以我想要的内爆和爆炸方式对其进行操作:
<form action="thispage.php" method="post">
(the previous fields here)
<input type="checkbox" name="interests[]" value="Politics
<input type="checkbox" name="interests[]" value="Entertainment
<input type="checkbox" name="interests[]" value="Tech
<input type="checkbox" name="interests[]" value="Health
<input type="checkbox" name="interests[]" value="Living
<input type="checkbox" name="interests[]" value="Travel
<input type="checkbox" name="interests[]" value="World
etc...
<input type="submit" value="Submit">
</form>
And the php (must go BEFORE the form):
和 php(必须在表单之前):
<?php
if (isset($_POST['interests'])) {
$interests_str = implode(" ", $_POST['interests']);// converts $_POST interests into a string
$interests_array = explode(" ", $interests_str);// converts the string to an array which you can easily manipulate
}
for ($i = 0; $i > count($interests_array); $i++) {
echo $interests_array[$i];// display the result as a string
}
?>
The advantage of this script is that you can access the $interests_array whenever you want in your document as a common array.
此脚本的优点是您可以随时访问文档中的 $interests_array 作为公共数组。
回答by Sujit Singh
hey, I have made it easy to create checkboxes as well as radio buttons in any php form. Only thing is I am using Codeigniter MVC framework.
嘿,我已经让在任何 php 表单中创建复选框和单选按钮变得容易。唯一的问题是我使用的是 Codeigniter MVC 框架。
Here is the function definition that you can insert in your common-model or any helper file.
这是您可以插入到您的通用模型或任何帮助文件中的函数定义。
function createOptions($fieldName, $labelsArray=array(), $selectedOption, $fieldType,$valuesArray = array()) {
$returnString = '';
if(count($valuesArray)!=count($labelsArray))
$valuesArray=$lebelsArray;
if ($fieldType === 'checkbox') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='   <input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />  <label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='  <input type="radio" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if($valuesArray[$i]== $selectedOption)
$returnString.=' checked="checked" ';
$returnString.=' /><label>'.$labelsArray[$i].'</label>';
}
}
return $returnString;
}
And, you have to call this function in view file as,
而且,你必须在视图文件中调用这个函数,
<?php
echo $this->common_model->createOptions('userHobbies[]', $hobbyOptions, $userHobbies, 'checkbox'); ?>
First parameter is name of checkbox field or radio field, which is always gonna be same for all options for both cases. Second is labels array, Third is selected options which will show those options as checked while loading the form. Fourth is type of field that will be a string as 'checkbox' or 'radio'. Fifth will be values array, which, if present, will contain values for labels in the same order as that of labels. If its absent, labels array will be teated as values array.
第一个参数是复选框字段或单选字段的名称,对于这两种情况的所有选项总是相同的。第二个是标签数组,第三个是选择的选项,它将在加载表单时将这些选项显示为已选中。第四个是字段类型,它将是一个字符串,如“复选框”或“收音机”。第五个是 values 数组,如果存在,它将包含与标签顺序相同的标签值。如果不存在,则标签数组将被视为值数组。
回答by John Bentley
The following is a general routine to handle array variables sent to a page, that are located among regular name/value variables.
以下是处理发送到页面的数组变量的通用例程,这些变量位于常规名称/值变量之间。
Example php:
示例 php:
<?php
/*
Summary: Output variables pushed to the page. Handle arrays that have been sent.
Remarks: $_REQUEST handles posts or gets.
*/
echo '<pre>';
foreach($_REQUEST as $name => $value){
if (is_array($value)) {
echo "$name:<br />";
// Assign array to something more mnemonic
$items = $value;
foreach ($items as $item) {
echo " $item<br />";
}
} else {
echo "$name: $value<br />";
}
}
echo '</pre>';
?>
Example Markup:
示例标记:
<form method="post"
enctype="application/x-www-form-urlencoded"
action="forms-process.php">
<label>Customer name: <input name="customerName" /></label>
<fieldset>
<legend> Pizza Toppings </legend>
<label> <input type="checkbox" name="toppings[]" value="bacon" /> Bacon </label>
<label> <input type="checkbox" name="toppings[]" value="cheese" /> Extra Cheese </label>
<label> <input type="checkbox" name="toppings[]" value="onion" /> Onion </label>
</fieldset>
<label><button>Submit order</button></label>
</form>
Example Output:
示例输出:
customerName: John
toppings:
bacon
cheese
回答by rajmohan
//options[] makes it an array
<form method="get">
<input type="checkbox" name="options[]" value="Politics"/> Politics<br/>
<input type="checkbox" name="options[]" value="Movies"/> Movies<br/>
<input type="checkbox" name="options[]" value="World "/> World<br/>
<input type="submit" value="Go!" />
</form>
You can access this array by $_GET['options']
您可以通过以下方式访问此数组 $_GET['options']
Try Print_r( $_GET['options'])
; to see the values in it.
尝试Print_r( $_GET['options'])
; 查看其中的值。
回答by barkah sugiharto
<form action="hitungmakan.php" method="post"><center>
<table border="1" width="400" cellpadding="3">
<tr><td colspan="5" align="center">Menu Makan dan Minum</td></tr>
<tr><td align="center">Makanan</td> <tdalign="center">Minuman</td></tr>
<tr>
<td><input name="makanan[]" type="checkbox" value="nasgor">nasi goreng $.7000<br>
<input name="makanan[]" type="checkbox" value="wuduk">wuduk $.6000<br>
<input name="makanan[]" type="checkbox" value="pecel">pecel $.9000</td>
<td><input name="minuman[]" type="checkbox" value="tehbotol">teh botol $.3000<br>
<input name="minuman[]" type="checkbox" value="campur">es campur $.7000<br>
<input name="minuman[]" type="checkbox" value="jeruk">es jeruk $.6000</td>
</tr>
<input type="submit" value="Total" name="total">
<input type="reset" value="Batal">