2014-10-01 43 views
1

我需要一个PHP数组,用于存储来自MySQL的数据并在以后的JQuery中使用。 从MySQL表提交后从PHP表格读取PHP数组的格式

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数据,类标识码)

$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代替数据。 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

'data.student_id [0] .class_id [0] .score' - 这并没有什么意义。为什么不'data [0] .student_id','data [0] .class_id','data [0] .score'? – wavemode 2014-10-01 03:57:31

+0

我真的很喜欢你的想法来访问每个属性。但是,我想知道如何获得每个班级的学生成绩。如果我们使用数据[0] .score,我们只能为每个学生访问一个分数。如果我错了,请纠正我。非常感谢@wavemode。 – nguyen 2014-10-01 04:30:57

+0

我想我们可以使用数据[student_id] [class_id] .score访问每个班级的学生成绩。再次感谢@wavemode。 – nguyen 2014-10-01 05:01:53

回答

0

尝试添加这使其复位键索引:

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

因为最终他们都已经由学生ID分组,$student_id[$j](包含001, 002等),重置键,这样就可以通过你的数字索引访问,而不是使用.001这是学生证

他们,