0

我有:

<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 用于索引“一”和“二”——我必须使用两个循环 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 ) ) ) 
4

2 回答 2

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();
  }
}
于 2012-09-09T13:25:57.027 回答
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
          }
   }
}
于 2012-09-09T13:26:07.673 回答