按小时分组时间值

时间:2013-11-28 16:32:59

标签: php mysql

我的查询结果如下:

05:02:00    
05:22:00    
05:48:00    
06:17:00    
06:41:00    
07:10:00    
07:27:00    
07:46:00

我想要实现的是这样:

5 - 02, 22, 48

6 - 17, 41

7 - 10, 27, 46

如何在PHP中完成?

2 个答案:

答案 0 :(得分:2)

SELECT HOUR(datetime) h, GROUP_CONCAT(MINUTE(datetime)) m
FROM table
GROUP BY h

答案 1 :(得分:1)

码(Demo on Codepad):

<?php
$result = array('05:02:00', // Your data array.
'05:22:00', 
'05:48:00',    
'06:17:00',    
'06:41:00',    
'07:10:00',    
'07:27:00',   
'07:46:00');

$end = array(); // Create array to hold grouped values.
foreach($result as $r) { // Loop over data array.
    $part = explode(':', $r); // Create array from strings.
    $end[$part[0]][] = $part[1]; // Store values inside $end array
}
echo '<pre>' . print_r($end, TRUE) . '</pre>'; // Echo array as preformatted text.
?>

输出:

Array
(
    [05] => Array
        (
            [0] => 02
            [1] => 22
            [2] => 48
        )

    [06] => Array
        (
            [0] => 17
            [1] => 41
        )

    [07] => Array
        (
            [0] => 10
            [1] => 27
            [2] => 46
        )

)

获取您要求的输出:

5 - 02, 22, 48
6 - 17, 41
7 - 10, 27, 46

而不是echo print_r()使用:

foreach($end as $hour => $minutes) {
    echo ltrim($hour, '0') . ' -';
    foreach($minutes as $index => $minute) {
        $comma = (($index + 1) == count($minutes)) ? '' : ',';
        echo ' ' . $minute . $comma;
    }
    echo '<br/>';
}