gmaggio
3/16/2016 - 10:51 AM

Programmatically create table that contains rowspan to distinguish date range based on month.

Programmatically create table that contains rowspan to distinguish date range based on month.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Table with date range</title>

<script type="text/javascript">
	
</script>

<style type="text/css">
	tr.odd {
		background: #eee;
	}
	tr.even {
		background: #fff;
	}
	td {
		vertical-align: top;
		padding: 5px;
	}
</style>

</head>

<body>
<?php
// Date range
$start_date = "2015-01-15";
$end_date   = "2016-03-15";

$date     = date("Y-m-d", strtotime($start_date)); // Currently viewed day
$month    = (int)(date("n", strtotime($date))); // Currently viewed month
$oldmonth = null;

$monthrow = "even"; // Month row group

$html = "<table>";

// Loop through the days within the date range
while(strtotime($date) <= strtotime($end_date)) {

	// Toggle between month row group
	if ($month != $oldmonth)
		$monthrow = ($monthrow == "odd") ? "even" : "odd";
	
	$html .= "<tr class='".$monthrow."'>";
	
	if ($month != $oldmonth){ // On start new month: display month & year, determine total deys
		
		// Determine the number of rows to merge
		// by counting the number of viewable days
		$maxdays   = (int)(date("t", strtotime($date))); // Total days whithin specified month
		$startday  = (int)(date("j", strtotime($date))); // Starting date being viewed
		$totaldays = $maxdays - ($startday - 1); // Total of viewable days
		
		$monthtitle  = date("F Y", strtotime($date)); // Month & year currently being viewed
		
		// Display month & year, and apply the row span to merge
		$html .= "<td rowspan='".$totaldays."'>".$monthtitle."</td>";
	}
	
	$html .= "<td>".$date."</td>"; // Display date
	$html .= "</tr>";
	
	$oldmonth = (int)(date("n", strtotime($date))); // Record old month
	$date = date("Y-m-d", strtotime("+1 day", strtotime($date))); // Add 1 day for next iteration
	$month = (int)(date("n", strtotime($date))); // Set new month
}

$html .= "</table>";

echo $html;
?>

</body>
</html>