我希望以下列格式创建一个列表:
2012 (2)
- January (1)
- March (1)
2011 (1)
- March (1)
来自以下格式的日期数组:
Array
(
[0] => Array
(
[year] => 2012
[month] => 3
)
[1] => Array
(
[year] => 2012
[month] => 1
)
[2] => Array
(
[year] => 2011
[month] => 3
)
)
此列表由以下查询提供,我也建议如何返回数据。这对我来说是最合乎逻辑的一步。
SELECT YEAR(post_date) as `year`, MONTH(post_date) as `month` FROM posts ORDER BY post_date DESC
我在这里死路一条。我不知道我是不是看到了一些显而易见的事情,或者我是否认为这太复杂了但我无法弄清楚从哪里开始。
答案 0 :(得分:2)
假设您可能有多个具有相同月/年的行:
# first sort into a 2-level array of post counts
$by_year = array();
$year_counts = array();
foreach ($rows as $row){
$by_year[$row['year']][$row['month']]++;
$year_counts[$row['year']]++;
}
# most recent year first!
krsort($by_year);
# and now iterate for display
foreach ($by_year as $year => $months){
echo "<b>$year</b> ($year_counts[$year])<br />\n";
echo "<ul>\n";
# sort jan->dec
ksort($months);
foreach ($months as $month => $num){
$name = date('F', mktime(0,0,0,$month,1,2010));
echo "<li> $name ($num) </li>\n";
}
echo "</ul>\n";
}
这可以按照您的要求使用此输入数据:
$rows = array(
array('year' => 2012, 'month' => 3),
array('year' => 2012, 'month' => 3),
array('year' => 2012, 'month' => 2),
array('year' => 2011, 'month' => 1),
);
输出:
2012 (3)
* February (1)
* March (2)
2011 (1)
* January (1)
*已更新以显示年份数
答案 1 :(得分:1)
然后你可以像这样构建数组:
$someArray = Array();
$query = mysql_query(...);
while (($row = mysql_fetch_assoc($query)) != NULL)
{
$someArray[] = Array("year" => $row['year'], "month" => $row['month']);
}
在这种情况下,$someArray[]
是“将此元素附加到数组上”的表示法。
答案 2 :(得分:1)
我猜你正在尝试创建一个每月有多少篇文章的列表,按年份按层次显示?
Neil的答案显示了如何从数据库中获取结果。如果您将其作为起点,那么您可以遍历数组并使用计数构建列表,然后打印出列表。
您也可以让MySQL使用group by语句计算每月的帖子数。
select year(post_date) as `year`, month(post_date) as `month`, count(*) as `count`
from posts
group by concat(year(post_date),month(post_date))
order by post_date desc
然后使用类似于Neil的代码,但为了以后的方便而制作一些嵌套数组,你得到:
$counts = array();
$query = mysql_query(...);
while (($row = mysql_fetch_assoc($query)) != null) {
$counts[ $row['year'] ] = array("month" => $row['month'], 'count' => $row['count']);
}
然后将其打印为HTML:
echo "<ul>";
foreach($counts as $year => $months) {
echo "<li>$year <ul>"
foreach($months as $row) {
$month = name_for_month($row['month']); //TODO: make this method
echo "<li>$month ({$row['count']})</li>";
}
echo "</ul></li>";
}
echo "</ul>";
嗯,你也有一年的总数。好吧,你可以添加类似的东西:
$yearSums = array();
$counts = array();
$query = mysql_query(...);
while (($row = mysql_fetch_assoc($query)) != null) {
$counts[ $row['year'] ] = array("month" => $row['month'], 'count' => $row['count']);
$yearSums[ $row['year'] ] += $row['count'];
}
然后打印出那些数据。
免责声明:不保证这是好的代码,这只是一个如何做到这一点的简单示例。