填充日历的最有效方法是什么?

时间:2014-03-25 11:48:14

标签: php mysql

我已经构建了一个简单的PHP日历,显示了12个月的时间。我有一个MySQL数据库,可以保存日历事件。我想用我的活动填充我的日历。我当然可以为每天运行一个MySQL查询,但365个查询似乎非常低效,运行单个MySQL查询并循环结果365次也是如此。什么,如果有的话,是替代品?有这样一种简单而有效的方法吗?

2 个答案:

答案 0 :(得分:0)

$query = "SELECT idEvent, day, hour , event from calendar where year = 2014 order by day, hour ";

$calendarEvents = array();

if ($result = $mysqli->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {

       $calendarEvents[  $row["day"]  ][ $row["idEvent"] ]  = $row;

  }

   /* free result set */
   $result->free();
}

然后你有来自2014年的数据和1个查询,并使用数组$ calendarEvents访问它们。 对于每天你都有id的所有事件,所以使用foreach循环,你得到当天的所有事件,其顺序与查询顺序相同

  for($i = 1; $i < 365 ; $i++){

 $date = date("Y-m-d" , strtotime( "2013-12-31 + $i day"));

     foreach( $calendarEvents[ $date ] as $idEvent => $c){

        echo $idEvent . " -- ".$date." - ". $c["hour"]." - ".$c["event"];

     }

 }

答案 1 :(得分:0)

要为您提供一年中每天一行的结果集,并将当天的所有事件(如果有)连接到另一列,您可以执行以下操作: -

SELECT DateSub.aDay, GROUP_CONCAT(CONCAT_WS(':', SomeCalendarTable.eventName, SomeCalendarTable.startTime, SomeCalendarTable.endTime)) AS DaysEvents
FROM
(
    SELECT DATE_ADD('2014/01/01', INTERVAL (Units.DayNo + Tens.DayNo * 10 + Hundreds.DayNo * 100) DAY) AS aDay
    FROM
    (SELECT 1 AS DayNo UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) Units,
    (SELECT 1 AS DayNo UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) Tens,
    (SELECT 1 AS DayNo UNION SELECT 2 UNION SELECT 3 UNION SELECT 0) Hundreds
    HAVING YEAR(aDay) = '2014' 
) DateSub
LEFT OUTER JOIN SomeCalendarTable
ON DateSub.aDay = SomeCalendarTable.calendarDate
GROUP BY DateSub.aDay