LoginSignup
0
1

More than 3 years have passed since last update.

生のPHPでカレンダーを作る

Last updated at Posted at 2020-08-21

背景

自分のためのメモ書きみたいなもんなのでめちゃくちゃ簡素です。すみません。
あまりに簡素すぎるので気が向いたときに機能追加していきます。
現状8月の設定でハードコーディングしてます。

コード

calendar.php
<?php
define("DAYS_OF_WEEK", 7);
define("MAX_WEEKS_OF_MONTH", 6);
define("NUMBER_OF_SQUARES", DAYS_OF_WEEK * MAX_WEEKS_OF_MONTH);
define("WEEK_DAYS", ['日', '月', '火', '水', '木', '金', '土']);

$_ = function($s) { return $s; };

$startDayPosition = date('w', strtotime('2020-08-01'));
$daysOfMonth = cal_days_in_month(CAL_GREGORIAN, 8, 2020);
$lastDayPosition = $daysOfMonth + $startDayPosition;
$weeksOfMonth = ceil($lastDayPosition / DAYS_OF_WEEK);
echo "<h1>2020年8月</h1>";
echo '<table>';

for ($d = 0; $d < count(WEEK_DAYS); $d++) {
    echo "<td>{$_(WEEK_DAYS[$d])}</td>";
}

echo "<tr>";

for ($squarePosition = 1; $squarePosition <= $lastDayPosition; $squarePosition++) {
    if($squarePosition - 1 >= $startDayPosition) {
        $dayCount = $squarePosition - $startDayPosition;
        echo "<td>$dayCount</td>";
    } else{
        echo "<td> </td>";
    }
    if ($squarePosition % DAYS_OF_WEEK === 0) {
        echo "</tr>";
    }
}

見た目

こうなります。
キャプチャ.PNG

for文二回以上使わないという条件でもっといい書き方があれば教えてください。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1