我在MySQL数据库中创建了一个表,其中包含整月的日期。
然后我试图在桌子上显示它们(看起来像日历)
我创建了一个脚本,因此每月的第一天显示在正确的日期(例如10月的周六)。
然后我会显示其后的所有其他日期。
代码
$Firstdate = date('Y-m-01');
$FirstDay = date("N", strtotime($Firstdate));
if ($FirstDay == 1) {}
if ($FirstDay == 2) { echo"<td></td>";}
if ($FirstDay == 3) { echo"<td></td> <td></td>";}
if ($FirstDay == 4) { echo"<td></td> <td></td> <td></td>";}
if ($FirstDay == 5) { echo"<td></td> <td></td> <td></td> <td></td>";}
if ($FirstDay == 6) { echo"<td></td> <td></td> <td></td> <td></td> <td></td>";}
if ($FirstDay == 7) { echo"<td></td> <td></td> <td></td> <td></td> <td></td> <td></td>";}
$result=mysql_query("SELECT * FROM calendar")or die('ERROR 315' );
$num_rows = mysql_num_rows($result);
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$TheDate = $row ['date'];
$TheDateF = date("jS", strtotime($TheDate));
echo " <td> $TheDateF</Center><br><br><br><br></td>";
if ($i % 7 == 0) {
echo '</tr><tr>'; // it's time no move to next row
}
}
这是从正确的一天开始,但是请看下面的截图,我需要它在星期日之后开始新的一行:
我有什么想法可以解决这个问题吗?
答案 0 :(得分:1)
试试这段代码。根据您的需要进行修改。我很确定这会对你有所帮助。
<?php
/* Set the default timezone */
date_default_timezone_set("America/Montreal");
/* Set the date */
$date = strtotime(date("Y-m-d"));
$day = date('d', $date);
$month = date('m', $date);
$year = date('Y', $date);
$firstDay = mktime(0,0,0,$month, 1, $year);
$title = strftime('%B', $firstDay);
$dayOfWeek = date('D', $firstDay);
$daysInMonth = cal_days_in_month(0, $month, $year);
/* Get the name of the week days */
$timestamp = strtotime('next Sunday');
$weekDays = array();
for ($i = 0; $i < 7; $i++) {
$weekDays[] = strftime('%a', $timestamp);
$timestamp = strtotime('+1 day', $timestamp);
}
$blank = date('w', strtotime("{$year}-{$month}-01"));
?>
<table class='table table-bordered' border=1 style="table-layout: fixed;">
<tr>
<th colspan="7" class="text-center"> <?php echo $title ?> <?php echo $year ?> </th>
</tr>
<tr>
<?php foreach($weekDays as $key => $weekDay) : ?>
<td class="text-center"><?php echo $weekDay ?></td>
<?php endforeach ?>
</tr>
<tr>
<?php for($i = 0; $i < $blank; $i++): ?>
<td></td>
<?php endfor; ?>
<?php for($i = 1; $i <= $daysInMonth; $i++): ?>
<?php if($day == $i): ?>
<td><strong><?php echo $i ?></strong></td>
<?php else: ?>
<td><?php echo $i ?></td>
<?php endif; ?>
<?php if(($i + $blank) % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endfor; ?>
<?php for($i = 0; ($i + $blank + $daysInMonth) % 7 != 0; $i++): ?>
<td></td>
<?php endfor; ?>
</tr>
</table>
来源 http://code.runnable.com/VKxpI5dzCMkTrRq1/simple-calendar-for-php