Php 将所选表单输入传递到后端
考虑一个简单的HTML表单,如Php 将所选表单输入传递到后端,php,html,forms,Php,Html,Forms,考虑一个简单的HTML表单,如 <form> <div> <input type='checkbox' name='selections[]' value='1' /> <input type='text' name="inputs[]" value='' /> </div> <div> <input type='checkbox' name='selections[]' value
<form>
<div>
<input type='checkbox' name='selections[]' value='1' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='2' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='3' />
<input type='text' name="inputs[]" value='' />
</div>
</form>
由于未选中复选框,从$inputs中删除
a
的简单方法是什么?i、 因此我可以更容易地循环这两个数组。这个答案需要对即将出现的内容有详细的了解。如果你想重复使用它,那就太糟糕了
对html页面进行以下假设:
- 行值从1开始
- 行值为升序
- 行值是连续的。e、 g.1、2、3。。。不是1,2,4
$len = count($selections);
for ($i = 0; $i < $len; $i++)
{
if (!in_array($i + 1, $selections))
unset($inputs[$i]);
}
$len=count($selections);
对于($i=0;$i<$len;$i++)
{
如果(!in_数组($i+1,$selections))
未设置($i)输入;
}
我可能会使用数组映射
$inputs = array_map(function($v) use ($inputs) {
return $inputs[$v - 1];
}, $selections);
尽管明顺的答案在转换为PHP时效果很好,但您应该像这样更改HTML:
<form method="post">
<div>
<input type='checkbox' name='data[0][selections]' value='1' />
<input type='text' name="data[0][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[1][selections]' value='2' />
<input type='text' name="data[1][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[2][selections]' value='3' />
<input type='text' name="data[2][inputs]" value='' />
</div>
<input type="submit"/>
<?php
echo '<pre>';
print_r($_POST['data']);
?>
或:
现在您可以循环结果并处理
这是一个PHP答案?称之为输入错误。现在修好了。Javascript和Java会让我忘记php变量的前缀是$symbol。php没有变量类型的语法。不需要
len
,只需将count($selections)
放入for
中即可。
<?php
echo '<pre>';
print_r($_POST['data']);
?>
Array
(
[0] => Array
(
[selections] => 1
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
Array
(
[0] => Array
(
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
$selections = array();
$inputs = array();
foreach ($_POST['data'] as $item){
if (!empty($item['selections']) && !empty($item['inputs'])){
$selections[] = $item['selections'];
$inputs[] = $item['inputs'];
}
}
var_dump($selections);
var_dump($inputs);