Reputation: 27
I'm trying to create a calendar system that will show what jobs are booked in for certain days, I want it to be a horizontal calendar that has all of the days of the months as a table row and days of the week as the next row. I've got the first row sorted but I need to have the second row repeat the array of the days of the week until the month ends.
//Establish How many days are in the current Month
$currentMonthDays = date("t");
$daysOfWeek = array('M','T','W','T','F','Sa','Su');
echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
<tr>';
for ($i = 1; $i <= $currentMonthDays; $i++)
{
echo '<td width="30" align="center">'.$i.'</td>';
}
echo '</tr><tr>';
foreach($daysOfWeek as $day){
echo '<td width="30" align="center">'.$day.'</td>';
}
echo '</tr>';
Upvotes: 1
Views: 427
Reputation: 5041
The easiest way to do this to use the DateTime
class and formatting methods you used to get the number of days to also format the date for you.
$currentMonthDays = date('t');
$month = date('m');
$year = date( 'Y');
for ($i = 1; $i <= $currentMonthDays; $i++) {
echo '<td width="30" align="center">'.$i.'</td>';
}
$day = new DateTime();
for ($i = 1; $i <= $currentMonthDays; $i++) {
$day->setDate( $year, $month, $currentMonthDays);
// this outputs first 3 letters of day, but you can truncate if you want..
echo '<td width="30" align="center">'.$day->format('D').'</td>';
}
You could also avoid the need for 2 loops by merging the two td
s and formatting the cell by either adding a br
element between the day of the month and the day of the week, or using CSS formatting.
Upvotes: 0
Reputation: 1582
Try below code
$currentMonthDays = date("t");
$daysOfWeek = array('M', 'T', 'W', 'T', 'F', 'Sa', 'Su');
echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
<tr>';
for ($i = 1; $i <= $currentMonthDays; $i++) {
if ($i % 7 == 1)
echo '</tr><tr>';
echo '<td width="30" align="center">' . $i . '</td>';
}
echo '</tr><tr>';
foreach ($daysOfWeek as $day) {
echo '<td width="30" align="center">' . $day . '</td>';
}
echo '</tr>';
maybe helps you.
Upvotes: 0
Reputation: 111
Try this :
//Establish How many days are in the current Month
$currentMonthDays = date("t");
$daysOfWeek = array('M','T','W','T','F','Sa','Su');
for ($i = 0; $i <= $currentMonthDays-1; $i++){
$arrayWeekDays[] = $daysOfWeek[($i%7)];
}
echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
<tr>';
for ($i = 1; $i <= $currentMonthDays; $i++)
{
echo '<td width="30" align="center">'.$i.'</td>';
}
echo '</tr><tr>';
foreach($arrayWeekDays as $day){
echo '<td width="30" align="center">'.$day.'</td>';
}
echo '</tr>';
Cheers :)
Upvotes: 1