teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

sample

2016/11/22 08:22

投稿

yambejp
yambejp

スコア117820

answer CHANGED
@@ -4,4 +4,64 @@
4
4
  aかbか''のどれかでしょうか?aとbの両方にカテゴライズされることはないのですか?
5
5
 
6
6
  いずれにしろ、テーブルとかんたんなサンプルを表記し、
7
- 期待する結果を提示していただいたほうが適切な回答がつきやすいと思います
7
+ 期待する結果を提示していただいたほうが適切な回答がつきやすいと思います
8
+
9
+ # sample
10
+ ```SQL
11
+ create table wp_posts(ID bigint(20) unsigned not null primary key auto_increment,post_date datetime);
12
+ insert into wp_posts values(1,'2016-01-01 00:00:00'),(2,'2016-01-01 01:00:00'),(3,'2016-01-02 00:00:00'),(4,'2016-02-01 00:00:00'),(5,'2016-02-01 01:00:00'),(6,'2016-03-01 00:00:00'),(7,'2017-01-01 00:00:00');
13
+
14
+ ```
15
+ だったとして、抽出するSQLは
16
+ ```SQL
17
+ select year(post_date) as year
18
+ ,month(post_date) as month
19
+ ,count(*) as count
20
+ from wp_posts
21
+ group by year,month
22
+ order by year desc,month desc;
23
+ ```
24
+ すると結果は
25
+ ```ここに言語を入力
26
+ year month count
27
+ 2017 1 1
28
+ 2016 3 1
29
+ 2016 2 2
30
+ 2016 1 3
31
+
32
+ ```
33
+ なり、PHPでいうとこんな感じ
34
+
35
+ ```ここに言語を入力
36
+ /*抽出部分は省略*/
37
+ $months=[
38
+ (object) ["year"=>2017,"month"=>1,"count"=>1],
39
+ (object) ["year"=>2016,"month"=>3,"count"=>1],
40
+ (object) ["year"=>2016,"month"=>2,"count"=>2],
41
+ (object) ["year"=>2016,"month"=>1,"count"=>3],
42
+ ];
43
+ $html="";
44
+ $pre_year=0;
45
+ foreach($months as $key=>$month){
46
+ $year=$month->year;
47
+ if($pre_year!==$year){
48
+ if($key>0){
49
+ $html.="</ul>\n";
50
+ $html.="</div>\n";
51
+ }
52
+ $html.="<div>\n";
53
+ $html.=sprintf("<h4>%s年</h4>\n",$year);
54
+ $html.="<ul>\n";
55
+ }
56
+ $html.=sprintf("<a href='#'>%s月(%s)</a></li>\n",$month->month,$month->count);
57
+ $pre_year=$year;
58
+ }
59
+ if(count($months)>0){
60
+ $html.="</ul>\n";
61
+ $html.="</div>\n";
62
+ }
63
+ print "<pre>\n";
64
+ print htmlspecialchars($html);
65
+ print "</pre>\n";
66
+
67
+ ```