2017-04-17 77 views
0

我有4個表。PHP Mysql選擇多個表,並製作多維數組我有4個表格

學生(id_student,名)

主題(id_subject,SUBJECT_NAME)

subject_category(id_subject_category,id_subject,subject_category)

得分(id_score,id_student,id_subject,id_subject_category,得分)

public function score(){ 
    $this->db->select('*'); 
    $this->db->from('student'); 
    $query0 = $this->db->get(); 
    $data=$query0->result_array(); 
    $j = 0; 


    while($j<count($data)){ 
     $sql2= "SELECT * FROM score where score.id_student = ?"; 
     $data2 = $this->db->query($sql2,$data[$j]['id_student']);   
     $data2 = $data2->result_array(); 
     $data[$j]['score'] = $data2; 
     $j++; 
     } 
    return $data; 
} 

結果是

Array 
(
    [final] => Array 
     (
      [0] => Array 
       (
        [id] => 1 
        [name] => John 
        [score] => Array 
         (
          [0] => Array 
           (
            [id_score] => 1 
            [id_student] => 1 
            [id_subject] => 2 
            [id_subject_category] => 1 
            [score] => 90 
           ) 
          [1] => Array 
           (
            [id_score] => 2 
            [id_student] => 1 
            [id_subject] => 2 
            [id_subject_category] => 2 
            [score] => 70 
           ) 
          [2] => Array 
           (
            [id_score] => 3 
            [id_student] => 1 
            [id_subject] => 2 
            [id_subject_category] => 3 
            [score] => 60 
           ) 


         ) 

       ) 

     ) 

) 

我需要這樣的

Array 
(
    [final] => Array 
     (
      [0] => Array 
       (
        [id] => 1 
        [name] => John 
        [score] => Array 
         (
          [id_subject] => Array 
           (
            [0] => Array 
             (
              [id_score] => 1 
              [id_student] => 1 
              [id_subject_category] => 1 
              [score] => 90 
             ) 
            [2] => Array 
             (
              [id_score] => 2 
              [id_student] => 1 
              [id_subject_category] => 2 
              [score] => 70 
             ) 
            [3] => Array 
             (
              [id_score] => 3 
              [id_student] => 1 
              [id_subject_category] => 3 
              [score] => 60 
             ) 

           ) 

         ) 

       ) 

     ) 

) 
+0

什麼那些之間的區別,我認爲只是鑰匙吧? – Omi

回答

0

陣列試試這個

public function score(){ 
$this->db->select('*'); 
$this->db->from('student'); 
$query0 = $this->db->get(); 
$data=$query0->result_array(); 
$j = 0; 


while($j<count($data)){ 
    $sql2= "SELECT * FROM score where score.id_student = ?"; 
    $data2 = $this->db->query($sql2,$data[$j]['id_student']);   
    $data2 = $data2->result_array(); 
    $data[$j]['score'][$data[$j]['id_student']] = $data2; 
    $j++; 
    } 
return $data; 
}