最长连续运动天数计算

最近在写健身馆app的接口,需要统计最长连续运动天数,自己计算的不是很准确。

public function getSustainedDays($accountId)
{
    $list = $this->getMotionDates($accountId);
    $times = 0;
    if ($list) {
        $i = 0;
        $j = 0;
        $dates = strtotime(date("Y-m-d",$list[0]['entry_time']));
        foreach ($list as $k => $v){
            if (strtotime(date("Y-m-d",$v['entry_time'])) == ($dates - 24*60*60*$j)) {
                $i++;
                $j++;
            } else {
                if ($i > $times) $times = $i;
                $i = 1;
                $j = 0;
                if ($k+1 < count($list)) $dates = strtotime(date("Y-m-d",$list[$k+1]['entry_time']));
            }
        }
        if ($i > $times) $times = $i;
    }
    return $times;
}
public function getMotionDates($accountId)
{
    $entryRecord = EntryRecord::find()
        ->alias('er')
        ->joinWith(['members m'], FALSE)
        ->where(['m.member_account_id' => $accountId])
        ->select('er.entry_time')
        ->groupBy(["DATE_FORMAT(from_unixtime(er.entry_time),'%Y-%m-%d')"])
        ->orderBy('er.entry_time desc')
        ->asArray()
        ->all();
    return $entryRecord;
}
自己写了半天,感觉挺好用的,但是测试那边给打回来了,统计的不准确。发现有一个账号中间有间隔的一天,

竟然统计成2天了。求大神指点。
慕标琳琳
浏览 490回答 3
3回答

阿波罗的战车

昨天又换了一种方法和雪之祈舞的有点相似: public function getSustainedDays($accountId) { $list = $this->getMotionDates($accountId); $len = 1; $max = 1; if ($list) { foreach ($list as $k => $v){ if ($k+1 == count($list)) break; if ((strtotime(date("Y-m-d",$list[$k]['entry_time'])) - 60*60*24) == strtotime(date("Y-m-d",$list[$k+1]['entry_time']))) { $len++; } else { if ($len > $max) $max = $len; $len = 1; } if ($len > $max) $max = $len; } } return $max; }

大话西游666

换个思路解决,不用多余的各种查询开销。在用户表里面加两个字段 {连续打卡天数,最后打卡日期}。打卡的时候判断最后日前是不是今天,如果是啥也不做;如果是昨天,打卡天数++,更新最后打卡日期;如果是前天或更久的日期,将打开天数改为1,更新最后打卡日期

慕容森

function getSustainedDays() { $list = [ ['entry_time'=>'2018-01-01'], ['entry_time'=>'2018-01-02'], ['entry_time'=>'2018-01-04'], ['entry_time'=>'2018-01-05'], ['entry_time'=>'2018-01-06'], ['entry_time'=>'2018-01-07'], ['entry_time'=>'2018-01-09'] ]; $times = 0; $max = count($list)-1; if ($list) { $arr = []; $i = 0; $j = 0; $dates = strtotime($list[0]['entry_time']); foreach ($list as $k => $v){ $now = strtotime( $v['entry_time']); if ($now == ($dates + 24*60*60*$j)) { $i++; $j++; echo $k; } else { array_push($arr,$i); $i = 1; $j=1; if ($k+1 < count($list)) $dates = $now; } if($k==$max){ array_push($arr,$i); } } print_r($arr); $times = max($arr); } return $times; } echo getSustainedDays();
打开App,查看更多内容
随时随地看视频慕课网APP