我有一个形式,其中几行输入可以相同几次,就像这样,
<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">
现在我必须将这些字段输入到数据库中,所以我循环访问了输入字段,它工作正常。
但我有一个问题:有时循环中的字段可能是空的。 即公司将有一个值,但没有类型。那么我该如何使循环应该在这样的键中输出空值:
Array(
company => array(
[0] => string0
[1] => string1
[2] => string2
)
type => array(
[0] =>
[1] => string1
[2] => string2
)
)
所以你可以看到类型的第一个键是空的,那么我该如何实现它,
我正在尝试这样做但没有结果,
$postFields = array('company', 'type');
$postArray = array();
foreach($postFields as $postVal){
if($postVal == ''){
$postArray[$postVal] = '';
}
else {
$postArray[$postVal] = $_POST[$postVal];
}
}
感谢任何帮助,
这个 HTML:
<input type="text" name="company[]"><input type="text" name="type[]">
将动态填充数组的键。我认为只要提交其中一个文本字段,您就永远不会得到空的0
元素。相反,您最终会得到数组长度不匹配的情况,您将无法确定省略了哪个数字。
解决方案是在 HTML 中显式声明键,如下所示:
<input type="text" name="company[0]"><input type="text" name="type[0]">
<input type="text" name="company[1]"><input type="text" name="type[1]">
<input type="text" name="company[2]"><input type="text" name="type[2]">
现在,您可以遍历数组,如果未设置某个键,则可以将其设置为空字符串:
foreach( range( 0, 2) as $i) {
if( !isset( $_POST['company'][$i]))
$_POST['company'][$i] = "";
if( !isset( $_POST['type'][$i]))
$_POST['type'][$i] = "";
}