PHP - 将基于持续时间的事件/行分组为单个html块

时间:2013-08-23 19:11:01

标签: php html mysql

所以我在一个表中有一堆'事件',它们有一个开始和结束列(都是DATETIME)。我在一天内获取每个事件,并且需要将它们组合在一起,以便它们可以显示为单个HTML块。

例如......

第1行:持续时间为30分钟,从09:00:00开始,到09:30:00结束 第2行:持续时间为30分钟,从09:30:00开始,到10:00:00结束 第3行:持续时间为90分钟,从12:00:00开始,到13:30:00结束

知道我需要2个html块的最佳方法是什么...一个是高度为60px的div(对于行1和2),然后因为在10:00:00之间有休息和12:00:00使另一个div高度为90px(第3行)。

这可以用MySQL以某种方式完成吗?或者我必须做一个PHP循环来检查空的时间空间,以便知道何时应该关闭div并开始一个新的?

任何帮助都会有所帮助。

这更像是一个逻辑问题,而不是代码问题。

2 个答案:

答案 0 :(得分:0)

您可以在MySQL中执行此操作。一种方法是使用相关子查询来确定“事件期”何时开始。新事件期间在与其他任何事件不重叠时开始。然后使用此信息为每个事件分配“事件期间ID”。

这样的查询在合适的索引中表现得相当不错。

你可以在php中这样做。我倾向于将这样的逻辑放入数据库而不是应用程序代码中。

答案 1 :(得分:0)

我个人的偏见是保持格式化数据库层。我会用PHP做到这一点。

基于问题文本的假设:

  1. 持续时间存储在数据库中

  2. 持续时间增量= 30分钟

  3. 事件不重叠。

  4. 使用ODBC

  5. 查询持续时间数据
  6. 持续时间查询包括ORDER BY Start_Time

  7. 将持续时间数据加载到适当的$ result变量中

  8. 每个事件的事件块为30px。

    $job_count = 0;
    
    $event_increment = 30;
    $event_height = 30;
    
    $this_block_height = 0;
    $this_block_content = "";
    
    
    while(odbc_fetch_row($result)) {
        //fetch all your results into arrays
        $duration[] = odbc_result($result, 1);
        $start_time[] = odbc_result($result, 2);
        $end_time[] = odbc_result($result,3);
        $event_count++;
    }
    
    for($x=0;$x < $event_count; $x++) {
        //loop through the arrays to format the blocks
        if($x + 1 == $job_count) {
            //if this is true, we are at the last element
            $this_block_height += $event_height; 
            $this_block_content .= $start_time[$x] . " to " . $end_time[$x] . PHP_EOL;
            echo "<DIV style='height:" . $this_block_height . "px;'>$this_block_content</DIV>";
        }
        else {
            if($end_time[$x] == $start_time[$x+1]) { 
                //if this is true there is no gap.
                $this_block_height += $event_height; 
                $this_block_content .= $start_time[$x] . " to " . $end_time[$x] . PHP_EOL;
            }
            else {
                 //gap identified
                 //write old block to file with padding on the end
                 //reset values to start over
                 $end_seconds = strtotime($end_time[$x]);
                 $start_seconds = strtotime($start_time[$x+1]);
                 $gap = $start_seconds - $end_seconds;
                 $gap_minutes = $gap / 3600;
                 $gap_increments = $gap_minutes / $event_increment;
                 $this_block_height += ($event_height * $gap_increments);
                 echo "<DIV style='height:" . $this_block_height . "px;'>$this_block_content</DIV>";
                 //this will put the space padding at the end of the first block
                 //instead of at the start of the second block  
                 $this_block_height = 0;
                 $this_block_content = "";
            }       
        }
    }