看思路是否有问题,还有其它更好的算法吧?
谢谢!
function get_calendar($year='',$month='')
{
$year = ($year == '' ? date('Y') : $year);
$month = ($month == '' ? date('n') : $month);

//获取当前月第一天的星期数
$start_weekday = date('w',strtotime($year.'-'.$month.'-1'));
//获取当前月的总天数
$days = date('t',strtotime($year.'-'.$month));

//数组,存放 7X6 个元素
$m = array();

//假设为 2009-5
/* 是把月历搞成如下形式:
日 | 一 | 二 | 三 | 四 | 五 | 六
______________________________
   |    |   |    |    | 1 | 2
 3 | 4  | 6 | 7  | 8  | 9 | 10
 ...
 31|    |   |    |    |   | 
 
*/
for($s = 0; $s < $start_weekday; $s++)
{
$m[$s] = '';
}

$m[$start_weekday] = 1;
$j = $start_weekday + 1;

for($s = 2; $s <= $days; $s++)
{
$m[$j] = date('w',strtotime($year.'-'.$month.'-'.$s));
$j++;
}
for($s = $j; $s < 42; $s++)
{
$m[$s] = '';
}

/*
形成如下数组( 经过调用后,print_r() 以下,
$arr = get_calendar();
echo '<pre>';
print_r($arr);
echo '</pre>';):
Array
(
[0] => Array
(
[0] => 
[1] => 
[2] => 
[3] => 
[4] => 
[5] => 1
[6] => 6
)

[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

[2] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

[3] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

[4] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

[5] => Array
(
[0] => 0
[1] => 
[2] => 
[3] => 
[4] => 
[5] => 
[6] => 
)
) */
return array_chunk($m,7);
}

//实际使用代码:
$arr = get_calendar($year,$month);
$num = 1;

$cot = count($arr);
echo '<table>';
for($i = 0; $i < $cot; $i++)
{
for($j = 0; $j < 7; $j++)
{
echo ($j == 0 ? '<tr">' : '').'<td">';
echo ($arr[$i][$j] == ''? '' : '<a href="?url=">'.($num++).'</a>');
echo '</td>'.($j == 6 ? '</tr>' : '');
}
}
echo '</table>';