我认为您的解决方案实际上需要在 PHP 中使用,并且不确定您是否可以通过查询直接从 MYSQL 获得您要查找的内容。据我了解,您想要运行查询,获取您定义的日期范围内的所有记录,然后让没有记录的日期有一个空行(或您决定的任何其他值......)。
我实际上会运行与选择日期范围之间的行相同的查询,并使用DatePeriod Class 生成一个包含开始日期和结束日期之间所有日期的数组。
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-10-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Y-m-d") . "<br>";
}
有了这个,我们就可以每天从$from_date跑到$end_date。
接下来,我们需要从数据库中取出其他行,根据我们拥有的daterange 对象查看哪些天有记录,哪些没有记录。
我相信这是一种可行的方法,它不是最干净的示例,而是对其进行了一些额外的工作,您可以使它更漂亮一些,但我认为这将满足您的需求。
代码中的数据库部分不在 Codeigniter 中,但由于它只是获取一个简单的查询,因此更改它应该没有任何问题。
// set the start & end dates
$from_date = '2012-09-11';
$to_date = '2012-11-11';
// create a daterange object
$begin = new DateTime($from_date);
$end = new DateTime($to_date );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$sth = $dbh->prepare("SELECT col1, dateCol from tb WHERE dateCol>'".$from_date."' AND dateCol<'".$to_date."' order by dateCol ");
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
$rowsByDay = array(); // will hold the rows with date keys
// loop on results to create thenew rowsByDay
foreach($rows as $key=>$row) {
$rowsByDay[strtotime($row['dateCol'])][] = $row; // add the row to the new rows array with a timestamp key
}
// loop of the daterange elements and fill the rows array
foreach($daterange as $date){
if(!isset($rowsByDay[strtotime($date->format("Y-m-d"))])) // if element does not exists - meaning no record for a specific day
{
$rowsByDay[strtotime($date->format("Y-m-d"))] = array(); // add an empty arra (or anything else)
}
}
// sort the rowsByDay array so they all are arrange by day from start day to end day
ksort($rowsByDay);
// just for showing what we get at the end for rowsByDay array
foreach ($rowsByDay as $k=>$v) {
echo date('Y-m-d',$k);
var_dump($v);
echo '<hr/>';
}
希望这能让你走上正确的道路......