你好,我正在尝试用我的数据库循环实现一些东西,但我没有解决方案。我想我已经接近解决方案,但真的需要帮助。我相信我需要在循环中循环,但不知道如何做到这一点。
如何使用PHP & SQL按月分组行,循环月份内的日期并跳到下个月?
数据如下所示:
Creation_date | Project_name
2023-02-24 | Project A
2023-02-22 | Project B
2023-02-22 | Project C
2023-02-21 | Project..
2023-02-13 | Project..
2023-01-28 | Project..
2023-01-20 | Project..
2022-12-31 | Project..
2022-12-02 | Project..
2022-11-09 | Project..
2022-10-26 | Project..
这是密码
<?php
$query = '
SELECT
Creation_date,
DATE_FORMAT(Creation_date, "%m") Creation_date_m,
DATE_FORMAT(Creation_date, "%M") Creation_date_M_full,
DATE_FORMAT(Creation_date, "%Y") Creation_date_Y_full,
Project_name
FROM Projects
ORDER BY Creation_date DESC
';
$result = $conn->query($query);
$previousMonth = null;
$currentMonth = date('m');
?>
<?php while ($row = $result->fetch_assoc()): ?>
<?php
$month = $row['Creation_date_m'];
$monthFull = $row['Creation_date_M_full'];
$year = $row['Creation_date_Y_full'];
if (!$previousMonth) {
$previousMonth = $currentMonth;
}
// if there is a change of month, define the class to be set
if ($month != $previousMonth) {
$previousMonth = $month;
$monthName = '<h2>' . $monthFull . ' ' . $year . '</h2>';
} else {
$monthName = "";
}
?>
<div class="month">
<?= $monthName; ?>
<div class="day-of-month"><?= $row['Creation_date']; ?></div>
</div>
<?php endwhile; ?>
现在我的循环输出如下:
<div class="month">
<h2>February 2023</h2>
<div class="day-of-month">2023-02-24</div>
</div>
<div class="month">
<div class="day-of-month">2023-02-22</div>
</div>
<div class="month">
<div class="day-of-month">2023-02-22</div>
</div>
<div class="month">
<h2>January 2023</h2>
<div class="day-of-month">2023-01-28</div>
</div>
<div class="month">
<div class="day-of-month">2023-01-20</div>
</div>
但它应该输出如下内容:
<div class="month">
<h2>February 2023</h2>
<div class="day-of-month">2023-02-24</div>
<div class="day-of-month">2023-02-22</div>
<div class="day-of-month">2023-02-22</div>
</div>
<div class="month">
<h2>January 2023</h2>
<div class="day-of-month">2023-01-28</div>
<div class="day-of-month">2023-01-20</div>
</div>
非常感谢,我希望这是清楚的:)
2条答案
按热度按时间gzszwxb41#
你只需要在月份div发生变化时输出它。类似于下面的代码(未测试):
如果月份发生变化,
$monthName
包含表头,$monthEnd
包含较近的月份,否则它们都为空。不需要检查
$previousMonth
是否为空,因为它与从数据库返回的月份仍然不同,但需要在每次输出行时更改它,而不是每次输出标题时。我不确定
$rowCountTable
从何而来,所以我在循环中将其更改为$row
。可能是这里的打印错误。ou6hu8tu2#
我不是PHP程序员(在所有),但基本结构应该是...
<\div>
和<div>
对上述内容的唯一警告是确保在第一个开始div之前编写了结束div。
如果我正确理解了php语法,下面的代码应该可以做到这一点。