考虑一个简单的HTML表单,如
<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>
有三行,假设只检查第二行,第三行,并且所有三个文本输入都填充了(a,b,c),所以在我的后端(PHP)中,我可以有两个数组
e.g。
$selections = array(2, 3);
$inputs = array('a', 'b', 'c');
由于未选中复选框,从$输入中删除a
的简便方法是什么?即所以我可以更容易地循环这两个数组。
答案 0 :(得分:0)
这个答案需要详细了解进入的内容。如果你想重复使用它,那就更糟了。
关于html页面正在做出以下假设:
以下是代码:
$len = count($selections);
for ($i = 0; $i < $len; $i++)
{
if (!in_array($i + 1, $selections))
unset($inputs[$i]);
}
答案 1 :(得分:0)
我可能会使用array_map
$inputs = array_map(function($v) use ($inputs) {
return $inputs[$v - 1];
}, $selections);
虽然如果转换为PHP
,MingShun的答案将正常工作答案 2 :(得分:0)
您应该像这样更改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']);
?>
结果:
Array
(
[0] => Array
(
[selections] => 1
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
OR:
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);