2016-01-06 180 views
1

我從三個MySQL表中提取數據以通過PHP中的AJAX和JSON生成引導數據表。我有多個組織單元(單元1,單元2,單元3等)。我也有多種程序類型(開始,中級和高級)。最後,我想爲每個組織單位並排顯示兩年的數據(2105和2014年)。JSON對象的索引數組元素

換句話說,所得到的表將像這樣被構造(與初節目類型虛擬值的一行):

    Unit 1  Unit 2  Unit 3 
       2015 2014 2015 2014 2015 - 2014 

Beginning  7  9  136 152  0  3 
Intermediate  
Advanced 

的JSON對象,將創建和填充此dataTable中需要看起來是這樣的:

[{"program_category":"Beginning","unit_1":{"2015":"7","2014":"9"}, 
"unit_2":{"2015":"136","2014":"152"}, 
"unit_3":{"2015":"0","2014":"3"}}] 

到目前爲止,我已經能夠編寫產生一個JSON字符串,讓我相當接近的SQL查詢,但你可以看到,「program_type」重演每個組織單位:

這裏的SQL:

select all_programs_test.program_category as program_category,  report_db.unit, 
    sum(case when all_programs_test.year = '2015' then 1 else 0 end) yr_2015, 
    sum(case when all_programs_test.year = '2014' then 1 else 0 end) yr_2014 
    from all_programs_test 
    JOIN report_db on report_db.id = all_programs_test.id 
    group by all_programs_test.program_category,report_db.unit 

然後我json_encode在PHP中:

while($row = mysql_fetch_assoc($query4)) { 
$query4_result[] = array ( 

'program_category' => $row['program_category'], 

$row['unit'] => array(
      '2015' => $row['yr_2015'], 
      '2014' => $row['yr_2014'] 
    ) 
); 

然後產生

[{"program_category":"Beginning","unit_1":{"2015":"7","2014":"9"}}, 
{"program_category":"Beginning","unit_2":{"2015":"136","2014":"152"}}, 
{"program_category":"Beginning","unit_3":{"2015":"0","2014":"3"}}] 

正如你可以在JSON對象片斷上面看到,「對每個組織單位重複「開始」。任何想法如何取而代之:

[{"program_category":"Beginning","unit_1":{"2015":"7","2014":"9"}, 
"unit_2":{"2015":"136","2014":"152"}, 
"unit_3":{"2015":"0","2014":"3"}}] 

謝謝!

回答

1

試試這個:

$category_aux = ''; 
$record_aux = array(); 

while($row = mysql_fetch_assoc($query4)) { 
    if ($category_aux !== $row['program_category']){ 
     $category_aux = $row['program_category']; 

     if (! empty($record_aux)) { 
      $query4_result[] = $record_aux; 
     } 

     $record_aux = array(); 

     $record_aux['program_category'] = $category_aux; 
    } 

    $record_aux[$row['unit']] = array(
     '2015' => $row['yr_2015'], 
     '2014' => $row['yr_2014'] 
    ); 
} 

// For the last one. 
$query4_result[] = $record_aux; 
+0

嗨,艾倫,只是試過你的解決方案,它的效果很好!非常感謝。 – tomish

+0

不客氣! :) – Allan

0

我已經構建了代碼的靜態版,試圖重現您的問題但它沒有問題的工作。

我認爲這個問題可能與您在查詢中的分組有關。你可以告訴我們查詢的結果嗎?