我一直在尝试根据发布的年份和月份显示数据库中的帖子,但无法做到这一点,因为我已尽我所能,但仍然认为这可以在 SQL 查询中完成并在 PHP 端支持它。下面是我的数据库结构
id | title | date
-------------------------------------------------
1 | hello this is a post | 2016-01-03 11:33 AM
2 | this is what i think | 2016-01-03 10:33 PM
3 | this is it | 2017-14-06 06:33 PM
4 | Blah Blah Blah | 2017-01-03 10:33 AM
5 | is what i think | 2016-04-03 10:33 PM
现在我想这样选择和分组
Your post on 2016-01-03
hello this is a post
this is what i think Your
post on 2017-14-06
this is it
Your post on 2017-01-03
Blah Blah Blah
Your post on 2017-01-03
is what i think
我试着用下面的代码来做这个
<?php
//I swear i don't know what else to do here
$db->prepare('SELECT * FROM post
GROUP BY ("")
ORDER BY date');
$db->execute();
$output = $db->getAll();
$db->free();
if(!is_null($output)){
foreach($output as $row){
$title = $row->title;
$date = $row->date;
/*
Only this path i got near but i can only display post for this month using $currentDate below.
But how can i get other once split according to date?
*/
$split = explode(" ", $date);
$currentDate = date('Y-m-d');
if($split[0] == $currentDate){
echo 'post on '.$currentDate.'<br/>'.$title;
}else{
echo 'post on '.$split[0].'<br/>'.$title;
}
?>
最佳答案
您在这里有三个要求。一种是在没有时间的情况下呈现帖子的日期。第二种是按日期/时间对帖子进行排序。
这些可以通过这样的查询来完成。
SELECT DATE(`date`) as date, `title` FROM post ORDER BY `date`
GROUP BY
对此没有任何作用。
第三个要求是,当连续发布的日期相同时,只呈现一次日期。这必须在 php 中完成。
$prev_date = "";
foreach ($output as $row) {
$title = $row->title;
$date = $row->date;
if ($date != $prev_date) {
echo "Posts on " .$date;
}
echo information about the post
$prev_date = $date;
}
诀窍是使用我命名为 $prev_date 的变量来检测日期何时从一行到另一行发生变化。
关于php - SQL 和 PHP 按发布的年、日和月对数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906280/