最近在写健身馆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天了。求大神指点。
3 回答
![?](http://img1.sycdn.imooc.com/5333a1660001394602000200-100-100.jpg)
阿波罗的战车
TA贡献1862条经验 获得超6个赞
昨天又换了一种方法和雪之祈舞的有点相似:
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;
}
![?](http://img1.sycdn.imooc.com/545861f00001be3402200220-100-100.jpg)
大话西游666
TA贡献1817条经验 获得超14个赞
换个思路解决,不用多余的各种查询开销。在用户表里面加两个字段 {连续打卡天数,最后打卡日期}。打卡的时候判断最后日前是不是今天,如果是啥也不做;如果是昨天,打卡天数++,更新最后打卡日期;如果是前天或更久的日期,将打开天数改为1,更新最后打卡日期
![?](http://img1.sycdn.imooc.com/545865620001c45402760276-100-100.jpg)
慕容森
TA贡献1853条经验 获得超18个赞
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();
- 3 回答
- 0 关注
- 489 浏览
添加回答
举报
0/150
提交
取消