我正在尝试使用PHP和MYSQL按月分组输出。在我提供一个简单的解决方案之前,在堆栈的帮助下。
if ($last_month != $month) {
$monthDiv = "<div class='monthSalute'>$month</div>";
$last_month = "$month";
} else {
$monthDiv = "";
}
足够简单,它很有意义。唯一的问题是月份变量,$last_month
每隔一段时间就会跳过一次。为了解释我上个月和月份做了一些var转储。注意跳过的月份。
string(8) "December"
string(8) "December"
string(7) "January"
string(7) "January"
string(0) ""
string(0) ""
string(7) "January"
string(7) "January"
string(5) "March"
string(5) "March"
string(5) "April"
string(5) "April"
最终输出如下:
**December -- header**
dec1 - game
dec5 - game
dec31 - game
**January -- header**
jan4 - game
jan7 - game
jan26 - game
**January -- header**
jan27 - game
jan31 - game
应该是
**January -- header**
jan4 - game
jan7 - game
jan26 - game
jan27 - game
jan31 - game
请注意,没有第二个1月标题。
以下是完整的代码作为参考。
<?php
// Check to see the URL variable is set and that it exists in the database
// Connect to the MySQL database
include "../../includes/db_conx.php";
//--------------------------------------------------------------------------------------
$sqlcount = "SELECT * FROM discounts WHERE team='cyoram' ORDER BY date ASC";
$sql_countRam = mysqli_query($db_conx,$sqlcount);
$calCount = mysqli_num_rows($sql_count);
//--------------------------------------------------------------------------------------
if ($calCount > 0) {
// get all the product details
$x=0;
while($row = mysqli_fetch_assoc($sql_countRam)){
$id = $row["id"];
$opponent = $row["opponent"];
$team = $row["team"];
$notes = $row["notes"];
$month = $row["month"];
$buyLink = $row["buyLink"];
$time = $row["time"];
$date = $row["date"];
$formatted_date = date("l d F Y H:i A", strtotime($date));
$raw = "$formatted_date";
$xplod = explode(' ',$raw);
/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
include "includes/logos.php";
/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
$classCssRam = "inline-block";
$x++;
$classChangeRam = ($x%2 == 0)? 'whiteBackground': 'grayBackground';
/* Print month heading for new month */
if ($last_month != $month) {
$monthDiv = "<div class='monthSalute'>$month</div>";
$last_month = "$month";
} else {
$monthDiv = "";
}
$product_listRam .= "
<div class='aNew' style='clear:both;display:$classCssRam;'>
$monthDiv
<table width='400px' border='0'>
<tr class='$classChangeRam'>
<td rowspan='2' class='date' >$xplod[1]</td>
<td class='day'>$xplod[0]</td>
<td rowspan='2' class='centerLogo'><div class='containImgPos'><img src='$imgLogo' height='32px' style='position:relative;left:$posImgR;' /></div></td>
<td class='city'>$city</td>
<td rowspan='2' class='butt_pad'><a href='calendar_edit.php?pid=$id'>edit</a> • <a href='calendar_list.php?deleteid=$id'>delete</a></td>
</tr>
<tr class='$classChangeRam'>
<td class='time $classChangeRam'>$time</td>
<td class='opponent $classChangeRam'>$opponent</td>
</tr>
</table>
</div>
";
}}
?>