回响历月的所有月份 [英] Echo all months with days calendar
问题描述
我正在使用以下代码回显当前月份。我该如何增强它,以便显示所有月份的名称,日期和日期。
I am using the code below to echo the current month. How can i enhance it so that is shows all the months with the names and days and dates..
代码:
<?php
$today = getdate();
$firstDay = getdate(mktime(0,0,0,$today['mon'],1,$today['year']));
$lastDay = getdate(mktime(0,0,0,$today['mon']+1,0,$today['year']));
?>
<?php
echo '<table>';
echo ' <tr><th colspan="7">'.$today['month']." - ".$today['year']."</th></tr>";
echo '<tr class="days">';
echo ' <td>Mo</td><td>Tu</td><td>We</td><td>Th</td>';
echo ' <td>Fr</td><td>Sa</td><td>Su</td></tr>';
?>
<?php
echo '<tr>';
for($i=1;$i<$firstDay['wday'];$i++){
echo '<td> </td>';
}
$actday = 0;
for($i=$firstDay['wday'];$i<=7;$i++){
$actday++;
echo "<td>$actday</td>";
}
echo '</tr>';
?>
<?php
$fullWeeks = floor(($lastDay['mday']-$actday)/7);
for ($i=0;$i<$fullWeeks;$i++){
echo '<tr>';
for ($j=0;$j<7;$j++){
$actday++;
echo "<td>$actday</td>";
}
echo '</tr>';
}
?>
<?php
if ($actday < $lastDay['mday']){
echo '<tr>';
for ($i=0; $i<7;$i++){
$actday++;
if ($actday <= $lastDay['mday']){
echo "<td>$actday</td>";
}
else {
echo '<td> </td>';
}
}
echo '</tr>';
}
?>
推荐答案
尝试一下:
function getDates($year)
{
$dates = array();
date("L", mktime(0,0,0, 7,7, $year)) ? $days = 366 : $days = 365;
for($i = 1; $i <= $days; $i++){
$month = date('m', mktime(0,0,0,1,$i,$year));
$wk = date('W', mktime(0,0,0,1,$i,$year));
$wkDay = date('D', mktime(0,0,0,1,$i,$year));
$day = date('d', mktime(0,0,0,1,$i,$year));
$dates[$month][$wk][$wkDay] = $day;
}
return $dates;
}
它将返回一系列的月->周->天->工作日传递给函数的年份。希望它应该很容易遍历数组以打印出所有内容。确保您可以进行很多调整,但这只是一个开始。
it will return an array of months->weeks->day->weekday of the year you pass to the function. Hopefully it should be easy to traverse through the array to print everything out. Am sure there are a lot of tweaks you can make to that but its a start.
例如,我还会尽量避免使用echo打印HTML;
I would also try and stay away from printing out html using echo, for example instead of;
echo '<tr>';
for($i=1;$i<$firstDay['wday'];$i++){
echo '<td> </td>';
}
do;
<tr>;
<?php for($i=1;$i<$firstDay['wday'];$i++){ ?>
<td><?php echo $var; ?></td>
<?php } ?>
我认为这会使代码更具可读性。
It kind of makes the code more readable I think.
编辑:只是认为我也应该包括一个用例的示例,如下所示:
Just thought I should include an example of a use case as well, as below:
<?php $dates = getDates(2011);
$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); ?>
<?php foreach($dates as $month => $weeks) { ?>
<table>
<tr>
<th><?php echo implode('</th><th>', $weekdays); ?></th>
</tr>
<?php foreach($weeks as $week => $days){ ?>
<tr>
<?php foreach($weekdays as $day){ ?>
<td>
<?php echo isset($days[$day]) ? $days[$day] : ' '; ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php } ?>
这会为您提供输出:
这篇关于回响历月的所有月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!