使用数组和memcached创建小时统计信息


Creating hour statistics using arrays and memcached

我正试图计算我的网站每小时有多少点击,但我不确定如何接近这个

这是我现在的文件:

if($cacheAvailable == true){ // WE GOT A CACHE
    date_default_timezone_set("UTC");
    $thisHour = date("H", time());
    $moveStats = $memcache->get('moveStats');
    if(!$moveStats){
        $todayStats = array(array(hour => $thisHour, hits => 1, executetime => $total_time));
        $memcache->set('moveStats', $todayStats);
    } 

    foreach ($moveStats as $k => $v) {
        if($v['hour'] == $thisHour){
            $moveStats[$k]['hits']=$moveStats[$k]['hits']+1;
        }
    }
    $memcache->set('moveStats', $moveStats);
    echo '<pre>';
    print_r($moveStats);
    echo '</pre>';
}

这使得数组如下:

Array
(
    [0] => Array
        (
            [hour] => 18
            [hits] => 6
            [executetime] => 0
        )
)

//##### EDIT ######//

我可以添加到当前的小时,但我不知道如何添加一个新的小时,当时钟变成新的小时?

希望得到帮助和提前感谢。

你只需要检查这个索引是否已经存在,如果没有创建一个新的,并且总是增加旧的值:

$todayStats = $moveStats;
if (!isset($todayStats [$thisHour])) {
    $todayStats[$thisHour] = 0;
}
$todayStats[$thisHour]['hits']++;
$todayStats[$thisHour]['executetime'] = $total_time;

但是在你的实现中有一些其他的问题:-不要使用没有引号的字符串。它将尝试调用具有该名称的常量,并且仅作为回退返回字符串本身。这也引起了注意。$thisHour不包含当前时间。如果您确实想要小时,请尝试:date('H') only。