我有下表:
CREATE TABLE `test` (
`id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`due_date` date NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test`(`id`, `title`, `due_date`) VALUES (1,'name1','2017-02-02');
INSERT INTO `test`(`id`, `title`, `due_date`) VALUES (2,'name2','2017-06-01');
INSERT INTO `test`(`id`, `title`, `due_date`) VALUES (3,'name3','2017-02-27');
INSERT INTO `test`(`id`, `title`, `due_date`) VALUES (4,'name4','2017-03-10');
INSERT INTO `test`(`id`, `title`, `due_date`) VALUES (5,'name5','2016-06-09');
我有用于打印我的数据的PHP代码:
$database = new Database();
$database->query("SELECT * from test");
$database->execute();
$arr = $database->resultset(); ?>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>due_date</th>
</tr>
</thead>
<tbody>
<?php foreach ($arr as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
现在我打印所有行。 我有due_date列,日期格式。 如何为三个catagorees分组我的数据:本周,下周和其他周(取决于due_date)。 这样做我的代码打印:
This week
id name due_date
3 name3 2017-02-27
Next week
4 name4 2017-03-10
Other week
1 ...
2 ...
5 ...
答案 0 :(得分:-1)
您询问的是SQL Group,但这不是您所需要的。您只需对查询进行排序,然后在循环中根据需要中断表。
$database->query("SELECT * from test WHERE due_date >= NOW() ORDER BY due_date");
WHERE子句不会显示过去的任务。检查您是否需要它。
然后在FOREACH语句中,您需要始终检查当前元素与已解析的最后一个元素
$lastDiff = -1;
$current_week = date('W') ;
foreach ($arr as $row):
array_map('htmlentities', $row);
$currentWeek = date('W', strtotime($row['due_date']));
$diff = $week - $current_week;
if ($lastDiff != $diff && $lastDiff < 2):
$lastDiff = $diff;
?><tr><td><?php echo week_name($diff) ?></td></tr>
<?php
endif;
?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr><?php
endforeach;
使用自定义函数修复标题分隔符,如下所示
function week_name($week)
{
switch ($diff) {
case 0:
$name = 'This Week';
break;
case 1:
$name = 'Next Week';
break;
default:
$name = 'Future Weeks';
break;
}
return $name;
}