我有一个 mysql 时间戳列表。我想制作一个 html 菜单,它的第一个 LI 有几年,嵌套 LI 有几个月。例如:
2012 -> 十二月、五月、四月。2011 年 -> 11 月,1 月。2010 -> 四月,三月,二月。
如您所见,我希望菜单是数年和数月内的数组,仅是我数据库中的数月(和数年)。
这肯定很简单,但我不知道如何执行此操作。我正在查询我所有的时间戳并循环它们,但是当我必须填充数组时,我无法管理。
你有没有尝试过这样的事情?
<?php
// this would've been pulled from mysql
$data = array(
array('date' => "2010-11-12 12:34:56", 'some' => 'data'),
array('date' => "2010-12-12 12:34:56", 'some' => 'data'),
array('date' => "2010-12-13 12:34:56", 'some' => 'data'),
array('date' => "2011-01-01 12:34:56", 'some' => 'data'),
);
$grouped = array();
foreach ($data as $row) {
$year = substr($row['date'], 0, 4);
$month = substr($row['date'], 6, 2);
$grouped[$year][$month][] = $row;
}
var_dump($grouped);
您想要的 SQL 可能是这样的:
SELECT YEAR(date) AS year, MONTH(date) AS month, COUNT(*) AS entries FROM my_table
GROUP BY year,month ORDER BY year ASC, month ASC;
代码是:
$previous_year = null;
foreach ($result_rows as $row) {
if ($previous_year == null || $row['year'] != $previous_year) {
if ($previous_year != null) {
echo '</ul>/li>';
}
echo '<li><span class="year">'.$row['year'].'</span><ul>';
$previous_year = $row['year'];
}
echo '<li>'.$row['month'].' ('.$row['entries'].')</li>';
}
if ($previous_year != null) {
echo '</ul></li>';
}
编辑:
基于另一个答案的替代 PHP,这是更整洁的:
$grouped = array();
foreach ($result_rows as $row) {
$grouped[$row['year']][$row['month']] = $row;
}
foreach ($grouped as $year => $months) {
echo "<li>$year";
echo "<ul>";
foreach ($months as $month => $row) {
echo "<li>$month (".$row['entries'].")</li>";
}
echo "</ul></li>";
}
您必须使用GROUP BY对查询进行分组,并在 PHP 中使用循环来创建合适的结构。
在轻微的peusdo代码中。
$r = query(SELECT * FROM TBL_WHATEVER ORDER BY TS ASC);
$last_year = null;
while($row as mysql_fetch_assoc($r)){
$year = date('Y', $r['ts']);
if($year != $last_year){
echo $year;
$last_year = $year;
}else{
$month = 1;
while($month < 12){
echo date('F', $r['ts']);
}
}
}
类似这样的帖子有很多: