0

我正在尝试建立一个年\月档案。

它拒绝输出我想要的东西,所以我希望你们中的一个人能把我推向正确的方向。

我想按年份排序,并显示每年的月份(如果存在)并像这样输出:

2012
 - June
 - August 
2011
 - July

我的代码是这样的:

$query = "SELECT * FROM article WHERE full_name ='$safe_name' group by year, month";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$year = $row['year'];
$month = $row['month'];
echo "<ul class='year'><li><a>{$year}</a>";
echo "<ul class='months'><li><a>{$month}</a></li></ul>
</li></ul>";
}

但它输出:

2012
 - june

2012
 - august

2011
 - july

当我只按年份分组时,它将输出:

2012
 - june
2011
 - july

我有一个“date_posted”行,它是日期时间(yyyy-mm-dd 00:00:00)。最重要的是,我每月有 1 行,每年有 1 行(我知道这很愚蠢,但我无法通过仅使用“date_posted”行来弄清楚如何做到这一点。

我已经阅读了有关此主题的一些帖子,但它对我没有用。任何帮助是极大的赞赏!

4

4 回答 4

1

您需要使用一个简单的“状态”机器来检测一年何时发生变化:

$previous_year = null;
$frist = true;
echo "<ul>"
while($row = mysql_fetch_assoc($result)) {
   if ($row['year'] != $previous_year) {
     // got a new year
     if (!$frist) {
        echo "</ul></li>"; // only close a previous list if there IS a previous list
        $frist = false;
     }
     echo "<li class="year">$row[year]\n<ul>";
     $previous_year = $row['year'];
   }
   echo "<li class="month">$row['month']</li>";
}
于 2012-08-02T15:43:27.297 回答
1
$temp_year = 0;
while($row = mysql_fetch_assoc($result)) {
    $year = $row['year'];
    $month = $row['month'];
    if( $temp_year != $year )
    {
        if( $temp_year > 0 )
            echo "</li></ul>";
        $temp_year = $year;
        echo "<ul class='year'><li><a>{$year}</a>";
    }
    echo "<ul class='months'><li><a>{$month}</a></li></ul>";
}
于 2012-08-02T15:44:00.307 回答
1

这应该有效。获取结果时,有时可以很方便地对其进行重组,以便在迭代视图时轻松使用。

$query = "SELECT * FROM article WHERE full_name ='$safe_name' group by year, month";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)) {

   // Get data
   $year = $row['year'];
   $month = $row['month']

   // Structure it
   $archive[$year][] = $month;

}

// Display data
foreach($archive as $year => $months)
{
   // Show year
   echo "<ul class='year'><li><a>{$year}</a>";

   // Month container
   echo "<ul class='months'>"

   // Get months
   foreach($months as $month)
   {
     echo("<li><a>{$month}</a></li>"; 
   }

   // Close Month/Year containers
   echo("</ul></li></ul>");
}
于 2012-08-02T15:45:31.803 回答
1

试一把

$storage_array = array();
while($row = mysql_fetch_assoc($result)) {
   $year = $row['year'];
   $month = $row['month'];
   $storage_array[$year][] = $month;
}
foreach ($storage_array as $year => $month_array){
   echo "<ul class='year'><li><a>{$year}</a>";
   foreach ($month_array as $month){
      echo "<ul class='months'><li><a>{$month}</a></li></ul>";
   }
   echo "</li></ul>";
}
于 2012-08-02T15:45:35.643 回答