用于多条记录的HTML表单


HTML form for multiple record

我希望用嵌套循环将多个记录保存在一个from中,如下所示。

<?php
   foreach($students as $student){
    foreach($student->$subjects as $subjects){
        <input name="grade[]" value="" />
    }
   }
?>

如何构造post['record']以下?

[records] => array(3) {
    [0]=> array(3) {
            ["'student_id'"] => string(1) "1", ["'subject_id'"] => string(1) "4", ["'grade'"] => string(1) "A"
        },
    [1]=> array(3) {
            ["'student_id'"] => string(1) "1", ["'subject_id'"] => string(1) "2", ["'grade'"] => string(1) "B"
        },
    [2]=> array(3) {
            ["'student_id'"] => string(1) "2", ["'subject_id'"] => string(1) "3", ["'grade'"] => string(3) "A+"
        }
}

你需要这样的东西吗:

$st = $student->id;
$su = $subject->id;
echo '<input type="text" name="grades[' . $st . '][' . $su . ']" value="" />';

然后,在接收POST的PHP脚本中,您可以访问如下等级:

foreach ( $_POST['grades'] as $student_id => $student_grades ) {
    foreach ( $student_grades as $subject_id => $grade ) {
        echo "student id: $student_id, ";
        echo "subject id: $subject_id, ";
        echo "grade:      $grade      <br>";
    }
}

输出:

student id: 1, subject id: 4, grade: A
student id: 1, subject id: 2, grade: B
student id: 2, subject id: 3, grade: A+

你看起来像这样吗?我想你已经有元素了

表单部件

<?php
$students=array(
    array('student_id'=>1,'subject_id'=>4),
    array('student_id'=>1,'subject_id'=>2),
    array('student_id'=>2,'subject_id'=>3),
);
foreach($students as $student){
    echo('<input name="grade[]" value="">');
    echo('<input type="hidden" name="records[]" value="'.serialize($student).'">');
}
?>

提交后

<?php
    $records=unserialize($_POST['records']);
    $grades=$_POST['grade'];
    // now mix both
    $i=0;
    foreach($grades as $grade) {
        $records[$i]['grade']=$grade;
        $i++;
    }
    print_r($records);
?>