提交表单后从JQuery读取的PHP数组的格式

时间:2014-10-01 03:50:59

标签: php arrays json

我需要一个PHP数组,它存储来自MySQL的数据,然后在JQuery中使用。 来自MySQL表的示例数据

student_id class_id score
001 01 A
001 02 B
002 02 A

在JQuery中,我想以data.student_id [i] .class_id [i] .score的形式访问这些数据 我该如何构造PHP数组?

我在view_student.php中的当前代码(可以选择多个student_id,class_id)

$student_id = $_POST['student_id'];
$class_id= $_POST['class_id'];

$student_array = array();

for($j=0;$j<sizeof($student_id);$j++) {
    $query = "SELECT class_id, score FROM student";
    $query .= " WHERE student_id='".$student_id[$j]."'";

    for($i=0;$i<sizeof($class_id);$i++){
        if($i==0) {
            $query .= " AND class_id=".$class_id[$i];
        } else {
            $query .= " OR class_id=".$class_id[$i];
        }
    }

    if($student_sql=$connection->query($query)){
        $student_php = array();
        $student_row_php = array();

        while($student_row_sql=$student_sql->fetch_array(MYSQLI_ASSOC)){
            $student_row_php["student_id"]=$sale_row_sql['student_id'];
            $student_row_php["score"]=$sale_row_sql['score'];
            array_push($student_php, $student_row_php);
        }
    }

    $student_array[$student_id[$j]]=$student_php;   
}
echo json_encode($student_array);

在JavaScript中,我需要data.student_id [0] .class_id [0] .score而不是data.001 [0] .score

<script>
$(document).ready(function() {
    $('form').submit(function(event) { 
        event.preventDefault(); /

        var postForm = new FormData(this);

        $.ajax({ 
            type        : 'POST', 
            url         : 'view_student.php', 
            data        : postForm, 
            processData: false,
            contentType: false,
            dataType    : 'json',
            success     : function(data) {
                $('#score').html('<font color="#FFFFFF"> <strong>'+data.001[0].score+'</strong> </font>');

            }
        });

    });
});

1 个答案:

答案 0 :(得分:0)

尝试添加它以便重置密钥索引:

$student_array = array_values($student_array); // simple reindex
echo json_encode($student_array);

由于最终它们已按学生ID $student_id[$j](包含001, 002等)分组,因此请重置您的密钥,以便您可以通过数字索引访问它们,而不是使用{ {1}}这是学生ID

相关问题