2013-07-24 62 views
0

我正在使用MySQL爲圖形生成數據。該圖需要包括當年的過去幾個月。例如:今天是七月份,圖表應該包括一月到七月。 SQL數據每個月都沒有數字。PHP將空白月份插入到foreach循環中

這裏是我的SQL輸出:

Units_Counted   Date 
    607     2 
    2120     5 
    42     7 

「日期」 字段的月份。 當我將它打印到圖表時,我需要它看起來像這樣。

Units_Counted   Date 
    0      1 
    607     2 
    0      3 
    0      4 
    2120     5 
    0      6 
    42     7 

這是我目前的PHP代碼。我需要在這裏添加另一個循環,但我似乎無法做到。

$Month = 1; 
foreach ($stmtIndividualGraphDatarows as $stmtIndividualGraphDatarow){ 
    if ($stmtIndividualGraphDatarow['GraphMonth'] == $Month) 
     { 
     echo "{"; 
      echo "'x': '".$stmtIndividualGraphDatarow['GraphMonth']."',"; 
      echo "'y':".$stmtIndividualGraphDatarow['GraphCounts']; 
     echo "},"; 
     } 
    else { 
     echo "{"; 
      echo "'x': '".$Month."',"; 
      echo "'y': 0"; 
     echo "},";} 
     $Month++; 
     } 

回答

1

希望我的代碼將有助於:

<?php 
$list = array(
    array(
     'GraphMonth' => 2, 
     'GraphCounts' => 607, 
    ), 
    array(
     'GraphMonth' => 5, 
     'GraphCounts' => 2120, 
    ), 
    array(
     'GraphMonth' => 7, 
     'GraphCounts' => 42, 
    ), 
); 
$max = 0; 

$month_count = array(); 
foreach ($list as $item) 
{ 
    $month = $item['GraphMonth']; 
    $count = $item['GraphCounts']; 
    if ($month > $max) 
    { 
     $max = $month; 
    } 
    $month_count[$month] = $count; 
} 

for ($i = 1; $i <= $max; $i++) 
{ 
    $month = $i; 
    $count = 0; 
    if (isset($month_count[$i])) 
    { 
     $count = $month_count[$i]; 
    } 
    $msg = "{'x': '$month', 'y': '$count'}"; 
    echo $msg, "\n"; 
} 
// output: 
//{'x': '1', 'y': '0'} 
//{'x': '2', 'y': '607'} 
//{'x': '3', 'y': '0'} 
//{'x': '4', 'y': '0'} 
//{'x': '5', 'y': '2120'} 
//{'x': '6', 'y': '0'} 
//{'x': '7', 'y': '42'} 
+0

我已經存儲在陣列中的數據。有沒有辦法把它整合起來,而不是把它全部拿出來再做一遍? – DarkSpartan47

+0

你的意思就像你這樣做的方式? – srain

+0

沒關係,我看你做了什麼。完善。謝謝 – DarkSpartan47