use this function could make the code more reusable:
function GetMonthInWeekArray ($mon, $year=2005)
{
// validate month value (1 - 12)
if ($mon < 1 || $mon > 12) return false;
// number of days in given month
$iNumDaysInMonth = date("t", mktime(0,0,0,$mon, 1, $year));
/**
* init the week array
*/
$aWeeks = array();
/**
* loop thru the days of given month
* put them into array of weeks
* @dim day in month
*/
for ($dim=1;$dim<=$iNumDaysInMonth;$dim++) {
/**
* the week number of this
* day in month
*/
$iWeekNum = date('W', mktime(0,0,0,$mon,$dim,$year));
/**
* day of the week
* 0 (for Sunday) through 6 (for Saturday)
*/
$iDayInWeek = date('w', mktime(0,0,0,$mon,$dim,$year));
/**
* convert day of the week to format of
* 0 (for Monday) through 7 (for Sunday)
* this is because the date('W') function
* treat Sunday as last day of the week
*/
if ((int)$iDayInWeek === 0) $iDayInWeek = 7;
if ($dim == 1){
/**
* if it's the first day of
* the month, fill the empty days
* of the week
*/
$aWeeks[$iWeekNum] = array_fill ( 1, $iDayInWeek-1, ' ');
$aWeeks[$iWeekNum][$iDayInWeek] = $dim;
} else if ($dim == $iNumDaysInMonth){
$aWeeks[$iWeekNum][$iDayInWeek] = $dim;
/**
* if it's the last day of
* the month, fill the empty days
* of the week
*/
for ($i=1;$i<8-$iDayInWeek;$i++){
$aWeeks[$iWeekNum][$iDayInWeek+$i] = ' ';
}
} else {
/**
* for regular days
*/
$aWeeks[$iWeekNum][$iDayInWeek] = $dim;
}
}
return $aWeeks;
}
$aWK = GetMonthInWeekArray(4, 2005);
print "<table border=1>";
print "<tr><td colspan=8>".date("F Y")." , Week ".date("W")."</td></tr>";
print "<tr>";
$weekdays = array('WK', "Mon","Tue","Wed","Thu","Fri","Sat","Sun");
foreach($weekdays as $weekday) {
print "<td bgcolor=lightblue>$weekday</td>";
}
print "</tr>";
foreach ($aWK as $w=>$v){
echo '<tr>';
echo '<td>'.$w.'</td>'; // week number
for($j=1;$j<=7;$j++){
echo '<td>'.$v[$j].'</td>'; // all other days
}
echo '</tr>';
}
/*
echo '<PRE>';
print_r(GetMonthInWeekArray(4, 2005));
echo '</PRE>';
*/