用于多条记录的HTML表单

时间:2015-03-30 01:36:08

标签: php html

我希望使用嵌套循环将多条记录保存在一个中。

<?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+"
        }
}

2 个答案:

答案 0 :(得分:0)

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

表单部分

<?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);

?>

答案 1 :(得分:0)

你需要这样的东西:

$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+