有效地根据时间(小时)分割数据

时间:2016-04-13 03:45:09

标签: php mysql

我所要做的实际上是与当天的一天中的小时相关的一组“投票”。

说我有这样的数据:

$array = array(
    array('vote' => 'up', 'timestamp' => '1460514600'),    //10.30am
    array('vote' => 'up', 'timestamp' => '1460514600'),    //10.30am
    array('vote' => 'down', 'timestamp' => '1460514600'),  //10.30am
    array('vote' => 'up', 'timestamp' => '1460514600'),    //10.30am
    array('vote' => 'down', 'timestamp' => '1460514600'),  //10.30am
    array('vote' => 'up', 'timestamp' => '1460529000'),    //2.30pm
    array('vote' => 'up', 'timestamp' => '1460529000'),    //2.30pm
    array('vote' => 'down', 'timestamp' => '1460529000'),  //2.30pm
);

我目前有以下内容将其划分为24小时制:

$new = array();
foreach($array as $element){
    $hour = date('H', $element['timestamp']);
    if(!isset($new[$hour])){
        $new[$hour] = array(
            'up' => 0,
            'down' => 0,
        );
    }
    // check & add
    switch($element['vote']){
        case "up":
            $new[$hour]['up']++;
            break;
        case "down":
            $new[$hour]['down']++;
            break;
    }

}

根据需要返回数据:

Array
(
    [10] => Array
        (
            [up] => 3
            [down] => 2
        )

    [14] => Array
        (
            [up] => 2
            [down] => 1
        )

)

是否有更有效的方法进行此分区?即使可以直接从Mysql中完成吗?

1 个答案:

答案 0 :(得分:2)

这里没有sql专家,但我最接近的就是使用一个简单的SUMCASE来计算所有投票的起伏情况GROUP BY格式化的小时(如果它确实保存为unix时间戳)。

SELECT 
    DATE_FORMAT(FROM_UNIXTIME(`timestamp`), '%H')
    AS group_hour,
    SUM(CASE WHEN vote = 'up' THEN 1 ELSE 0 END) AS total_up,
    SUM(CASE WHEN vote = 'down' THEN 1 ELSE 0 END) AS total_down
FROM table_name

GROUP BY `group_hour`

Somewhat of a demo