カレンダーを作る2

今回は週間カレンダーを作成します

前回のソースで、Smaryに配列を渡すこともやりました。今回は少しPHPのソースが複雑になっています。
今日の日付の取得と、今日が何曜日であるかを見て、週の頭(日曜日はじまり)から日付の算出を行います。

PHPソースは下記の通り

<?php
//mySmartyをrequire_onceする

$smarty = new MySmarty();
//週を表示する
$week = array(
‘日’,
‘月’,
‘火’,
‘水’,
‘木’,
‘金’,
‘土’,
);
$smarty->assign( ‘week’, $week );
$smarty->assign( ‘today’, date(‘d’) );

$today_week = date(‘w’);

//週の初めの日付を算出
$week_startDate = time() – $today_week * ( 24 * 60 * 60 );

$this_week = array();
for( $n = 0; $n < 7; $n ++ ){
//今週の日付を配列に格納する 日曜日から土曜日の順
$this_week[$n] = date(‘d’, $week_startDate + ( $n * ( 24 * 60 * 60 ) ) );
}
$smarty->assign( ‘this_week’, $this_week );

$smarty->display( ‘smarty01/lesson02.tpl’ );
?>

Smartyのテンプレートは以下のとおり

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<title>一週間の表示</title>

</head>
<body>
<div style=”text-align:center;”>
<table border=”1″>
<tr>
{foreach from=$week item=node}<th style=”background-color:#A0FFA0;padding:3px;”>{$node}</th>{/foreach}

</tr>
<tr>
{foreach from=$this_week item=node}<td style=”padding:3px;text-align:center;{if $node == $today}background-color:blue;color:white;{/if}”>{$node}</td>{/foreach}

</tr>
</table>
</div>
</body>
</html>

結果はこちら