简体   繁体   中英

PHP. displaying a calendar for all 12 months when the user selects this option

I have an assignment that includes a "select whole year" checkbox. When the user checks this box and submits, 12 calendars will display, one for each month. I have this working except for the month of June. All calendars, except June, display perfectly. The days for June are not in calendar form but rather spread out across the page. I don't understand how this is occurring or how to fix it. I would appreciate some help.

 if ($isPostBack) { $whole_year = filter_input(INPUT_POST, 'whole_year'); $select_year = filter_input(INPUT_POST, 'select_year', FILTER_VALIDATE_FLOAT); $select_month = filter_input(INPUT_POST, 'select_month', FILTER_VALIDATE_FLOAT); if ($whole_year) { $months_to_show = NUMBER_MONTH; } else { $months_to_show = 1; } $start_date = date_create_from_format('Ym-d', "{$select_year}-{$select_month}-01"); while ($months_to_show > 0) { $calendar = <<<CALENDAR <table> <tr><th colspan="7" style="text-align:center">{$start_date->format('F')} {$start_date->format('Y')}</th></tr> <tr> <th>Sun</th> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> </tr> <tr> CALENDAR; echo $calendar; $week_starts = $start_date->format('w'); for ($fillers = 0; $fillers < $week_starts; $fillers++) { echo "<td></td>"; } $day_of_week = $week_starts; for ($day_of_month = 1; $day_of_month <= $start_date->format('t'); $day_of_month++) { if ($day_of_week === 0) { echo '<tr>'; } echo "<td><a href='date.php?date={$select_year}-{$start_date->format('M')}-{$day_of_month}'>{$day_of_month}</a></td>"; if ($day_of_week === 6) { echo '</tr>'; $day_of_week = 0; } else { $day_of_week++; } } echo "</table>"; $start_date->modify('+1 month'); $months_to_show--; } } else { } ?> </body> </html> 

Your problem comes if the first day of the month is Sunday. You use the identical operator === that checks if the type of the two variables are the same too. However, your variable $week_starts is first initialize with $start_date->format('w'); that always returns a string. So the condition if ($day_of_week === 6) returns false . Then, when PHP will evaluate $day_of_week++; , it will cast the variable to an integer. You will have the serie '6', 7, 8, 9, ... and your table row will never be closed.

If the first day of the month is not a sunday, the variable will be cast to an integer before 6 and things will go fine : '3', 4, 5, 6, 0, 1, 2, 3, ...

So, two solutions :

  • Cast $week_starts to an integer at the beginning : $week_starts = intval($start_date->format('w'));
  • Use the simple equal operator == that will not check the types of the two variables : if ($day_of_week == 6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM