我有:
<form action="save.php" method="POST">
<input type="text" name="test[one][]" value="a"><input type="text" name="test[two][]" value="a"> <br />
<input type="text" name="test[one][]" value="s"><input type="text" name="test[two][]" value="s"><br />
<input type="text" name="test[one][]" value="d"><input type="text" name="test[two][]" value="d"><br />
<input type="text" name="test[one][]" value="f"><input type="text" name="test[two][]" value="f"><br />
<input type="text" name="test[one][]" value="g"><input type="text" name="test[two][]" value="g"><br />
<input type="submit">
</form>
在数据库中:
Table:
id | one | two
PHP中的我想制作:
if($_POST){
foreach($_POST['test'] as $post){
$new = new Table();
$new->setOne($post['one']);
$new->setTwo($post['two']);
$new->save();
}
}
但这不起作用......我不能使用POST作为索引&#39;一个&#39;和&#39;两个&#39; - 我必须使用两个循环foreach。可以用foreach中的一个foreach或foreach制作吗?
print_r($ _ POST)回复我:
[test] => Array ( [one] => Array ( [0] => a [1] => s [2] => d [3] => f [4] => g ) [two] => Array ( [0] => a [1] => s [2] => d [3] => f [4] => g ) ) )
答案 0 :(得分:3)
我会这样:
if (!empty($_POST)) {
// now $_POST['test'] is array('one' => array(), 'two' => array()
for ($i = 0, $c = count($_POST['test']['one']); $i < $c; ++$i) {
$new = new Table();
$new->setOne($_POST['test']['one'][$i]);
$new->setTwo($_POST['test']['two'][$i]);
$new->save();
}
}
答案 1 :(得分:0)
if(is_array($_POST['test'])){ // also check that the user submitted an array
foreach($_POST['test'] as $post){
$new = new Table();
foreach ($post['one'] as $item) { // $post['one'] and $post['two'] should have the same number of elements so looping through $post['one'] is sufficient to get entries for $post['two']
$new->setOne($item);
$new->setTwo($item);
$new->save(); // each item is saved in the database now
}
}
}