課題で月送り機能のついたカレンダーを作成しています。
<をクリックした際には先月のカレンダーを、>ボタンで翌月のカレンダーを表示したいです。
現在先月のカレンダー表示に挑戦しているのですが、表示されるのは曜日のみで日にちが出力されません。
Notice (8): Undefined variable: calendar [APP\View\Calendar\index.ctp, line 21]
Warning (2): Invalid argument supplied for foreach() [APP\View\Calendar\index.ctp, line 21]
というエラーが出ています。
エラーの意味は調べたら分かったのですが、どのように対処すべきかが分からない状況です。
アドバイスを頂けると嬉しいです。
以下コードです。
View
lang
1<?=$year?>年<?=$month?>月 2<?php echo $this->Html->link('<', ['action' => 'prev', '?' => ['last_month' => $month - 1], ['last_year' => $year]])?> 3//今月 4//翌月 5 6<table> 7 <tr> 8 <th>日</th> 9 <th>月</th> 10 <th>火</th> 11 <th>水</th> 12 <th>木</th> 13 <th>金</th> 14 <th>土</th> 15 </tr> 16 17 <tr> 18 <?php $cnt = 0; ?> 19 <?php foreach ($calendar as $key => $value): ?> 20 21 <td> 22 <?php $cnt++; ?> 23 <?php echo $value['day']; ?> 24 </td> 25 26 <?php if ($cnt == 7): ?> 27 </tr> 28 <tr> 29 <?php $cnt = 0; ?> 30 <?php endif; ?> 31 32 <?php endforeach; ?> 33 </tr> 34</table>
controller
lang
1public function index(){ 2 $year = date('Y'); 3 $month = date('m'); 4 5 $this->set(compact('year', 'month')); 6 7 $last_day = date('j', mktime(0, 0, 0, $month + 1, 0, $year)); 8 9 $calendar = array(); 10 $j = 0; 11 12 13 for ($i = 1; $i < $last_day + 1; $i++) { 14 $week = date('w', mktime(0, 0, 0, $month, $i, $year)); 15 16 if ($i == 1) { 17 for ($s = 1; $s <= $week; $s++) { 18 $calendar[$j]['day'] = ''; 19 $j++; 20 } 21 } 22 23 $calendar[$j]['day'] = $i; 24 $j++; 25 26 if ($i == $last_day) { 27 for ($e = 1; $e <= 6 - $week; $e++) { 28 $calendar[$j]['day'] = ''; 29 $j++; 30 } 31 } 32 33 $this->set(compact('calendar')); 34 35 } 36} 37 38 39public function prev(){ 40 // パラメータの取得 41 $last_month = $this->request->query('last_month'); 42 $last_year= $this->request->query('last_year'); 43 44 $year = date('Y'); 45 $month = date('m'); 46 47 $this->set(compact('month', 'year', 'last_month', 'last_year', 'calendar')); 48 49 $this->render('index'); 50 51 //$last_day = date('Y-m-d', mktime(0, 0, 0, $last_month, 0, $last_year)); 52 $date = new DateTime(); 53 $last_day = $date->format('t'); 54 55 $calendar = array(); 56 $j = 0; 57 58 for ($i = 1; $i < $last_day + 1; $i++) { 59 $week = date('w', mktime(0, 0, 0, $last_month, $i, $last_year)); 60 if ($i == 1) { 61 for ($s = 1; $s <= $week; $s++) { 62 $calendar[$j]['day'] = ''; 63 $j++; 64 } 65 } 66 67 68 $calendar[$j]['day'] = $i; 69 $j++; 70 71 72 if ($i == $last_day) { 73 for ($e = 1; $e <= 6 - $week; $e++) { 74 $calendar[$j]['day'] = ''; 75 $j++; 76 } 77 } 78 79 $this->set(compact('calendar')); 80 81 82 $year = $last_year; 83 $month = $last_month; 84 85 86 }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。