我必须将数据库的数据放在这种格式中(显然值会有所不同),我认为它被称为关联数组(我对术语很糟糕)。
$values=array(
"Jan" => 110,
"Feb" => 130,
"Mar" => 215,
"Apr" => 81,
"May" => 310,
"Jun" => 110,
"Jul" => 190,
"Aug" => 175,
"Sep" => 390,
"Oct" => 286,
"Nov" => 150,
"Dec" => 196
);
这是我开发的内容:
$sql = "SELECT MONTH(AddDate) AS Date, column_name FROM table ORDER BY AddDate ASC";
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
if ( $row['Date'] != $prev_date) {
$month = $row['Date'];
$sql = "SELECT count(MONTH(AddDate)) AS EntryAmount FROM `table` WHERE MONTH(AddDate)=$month ";
$countResults = mysql_query($sql) or die(mysql_error());
if( $entryAmount = mysql_fetch_array($countResults) ) {
$values[$row['Date']] = $entryAmount['EntryAmount'];
}
$prev_date = $row['Date'];
}
}
输出:
Array ( [9] => 999 [10] => 986 [11] => 264 )
答案 0 :(得分:5)
您可以在一个查询中完成所有这些操作:
select month(AddDate) as theMonth,
count(*) as numberOfRows
from `table`
group by theMonth
order by theMonth
然后外环消失,内环变为:
if( $row = mysql_fetch_array($results) )
{
$values[$row['theMonth']] = $row['numberOfRows'];
}
对于中等大小的数据集,它应该表现得更好。但请注意,通过使用month
函数,您将失去您可能能够使用的索引的任何好处。
答案 1 :(得分:0)
使用GROUP BY(未经测试):
$sql = "SELECT MONTH(AddDate) AS Date, count(AddDate) AS EntryAmount FROM table ORDER BY AddDate ASC GROUP BY MONTH(AddDate)";
$res = mysql_query($sql) or die(mysql_error());
$values=array();
while ( $row = mysql_fetch_assoc($res) ) {
$values[$row['Date']] = $row['EntryAmount'];
}