用PHP显示12个月的数据

时间:2013-09-19 14:42:05

标签: php mysql

我有查询:

SELECT MONTH(tgl) AS month, SUM(jumlahA) AS A, SUM(jumlahB) AS B
FROM tabel where YEAR(tgl)='2002' GROUP BY MONTH(tgl) order by 1;

结果是:

month   A       B
----------------------
1       85      0
2       38      0
9       34      23

问题是如何在PHP中完全显示一年(12个月)的数据,其中月份没有数据将0放到A和B.实际上我想创建带月轴的条形图(jan,feb,.. 。,des)

更新

这里有一些我的PHP代码:

echo "<categories>\n"; 
    echo "<category name='Jan' />\n"; 
    echo "<category name='Feb' />\n"; 
    echo "<category name='Mar' />\n"; 
    echo "<category name='Apr' />\n"; 
    echo "<category name='Mei' />\n"; 
    echo "<category name='Jun' />\n"; 
    echo "<category name='Jul' />\n"; 
    echo "<category name='Agu' />\n"; 
    echo "<category name='Sept' />\n"; 
    echo "<category name='Okt' />\n"; 
    echo "<category name='Nop' />\n"; 
    echo "<category name='Des' />\n"; 
echo "</categories>\n";

echo "<dataset seriesname='Hulu' color='AFD8F8'>"; 
$strQuery="SELECT MONTH(tgl) AS month, SUM(jumlahA) AS A, SUM(jumlahB) AS B FROM tabel where YEAR(tgl)='2002' GROUP BY MONTH(tgl) order by 1"; 
$hasil=mysql_query($strQuery); 
while ($data = mysql_fetch_array($hasil)) { 
    echo "<set value='".$data[1]."' />"; 
} 
echo "</dataset>";

1 个答案:

答案 0 :(得分:1)

使用与array返回的相同值制作MONTH(tgl) AS month。假设这些值与类别相同(如果不是,您可以更改它),请执行以下操作:

$months = array('Jan'=>null, 'Feb'=>null, 'Mar'=>null, 'Apr'=>null, 'Mei'=>null, 
'Jun'=>null, 'Jul'=>null, 'Agu'=>null, 'Sept'=>null, 'Okt'=>null, 'Nop'=>null, 'Des'=>null); 

尼斯。现在将您的while更改为:

while ($data = mysql_fetch_array($hasil)) { 
    $months[$data[0]] = "<set value='".$data[1]."' />"; 
} 

现在,在数组中,你得到的每个月都分别带有值。没有价值的月份是NULL s。现在很简单:

foreach ($months as $month) {
    if ($month) {
        echo $month;
    }
    else {
        echo "<set value='0' />";
    }
}

这是我的想法,我没有测试它,我希望它有效和有帮助!