[英]PHP Sorting data mysql by day per week
I have been trying to find solution to this issue. 我一直在寻找解决此问题的方法。 So here I give an example :
所以这里我举一个例子:
date item
-------------------
1-Jan-19 aaa
2-Jan-19 bbb
3-Jan-19 ccc
4-Jan-19 ddd
5-Jan-19 eee
6-Jan-19 fff
7-Jan-19 ggg
8-Jan-19 hhh
9-Jan-19 iii
10-Jan-19 jjj
11-Jan-19 kkk
So far I try with this code, but this its only show data separated by 7 data per row. 到目前为止,我尝试使用此代码,但这仅显示每行7个数据分隔的数据。 This code that I use,
我使用的这段代码
<?php
$i = 0;
$limit = 7;
$query = mysqli_query("SELECT * FROM mytable");
foreach ($query as $query) {
if ($i >= $limit) {
echo "<tr></tr>";
$i = 0;
}
$i++;
?>
<td><?php echo $query['item'];?></td> <?php } ?>
that show, 这就是如何,
#monday #tuesday #wednesday #thursday #friday #saturday #sunday
aaa bbb ccc ddd eee fff ggg
hhh iii jjj kkk
I want to show data like this, 我想显示这样的数据,
#monday #tuesday #wednesday #thursday #friday #saturday #sunday
--- aaa bbb ccc ddd eee fff
ggg hhh iii jjj kkk
How to fix this? 如何解决这个问题? No need to show name of days, above just for example
无需显示日期名称,例如
As explained in the comments, this can be done with pure SQL. 如注释中所述,这可以使用纯SQL完成。
You can use conditional aggregation to pivot the data over the days of the week, and group them by week of the year. 您可以使用条件聚合来调整一周中各天的数据,并按一年中的几周进行分组。 I used a subquery to avoid repeating conversions (and typing...) in the outer query.
我使用子查询来避免在外部查询中重复转换(和键入...)。
SELECT
t.week_year,
MAX(CASE WHEN t.week_day = 1 THEN t.item END) monday,
MAX(CASE WHEN t.week_day = 2 THEN t.item END) tuesday,
MAX(CASE WHEN t.week_day = 3 THEN t.item END) wednesday,
MAX(CASE WHEN t.week_day = 4 THEN t.item END) thursday,
MAX(CASE WHEN t.week_day = 5 THEN t.item END) friday,
MAX(CASE WHEN t.week_day = 6 THEN t.item END) saturday,
MAX(CASE WHEN t.week_day = 0 THEN t.item END) sunday
FROM (
SELECT
date,
item,
DATE_FORMAT(date, '%w') week_day,
DATE_FORMAT(date, '%Y-%v') week_year
FROM mytable
) t
GROUP BY t.week_year
ORDER BY t.week_year
Tips : 提示 :
'%w'
is the day of the week, where 0 is Sunday and 6 is Saturday '%w'
是星期几,其中0是星期日 ,6是星期六 %v
is the week of the year, where Monday is the first day of the week %v
是一年中的一周,其中星期一是一周中的第一天 This answer assumes that the date
column is of date datatype ( DATE
, DATETIME
, TIMESTAMP
). 该答案假定
date
列的日期数据类型为DATE
, DATETIME
, TIMESTAMP
。 If not, you would need to add a conversion in the subquery, using STR_TO_DATE
. 如果不是,则需要使用
STR_TO_DATE
在子查询中添加转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.