最近在寫健身館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 回答

阿波羅的戰車
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;
}

大話西游666
TA貢獻1817條經驗 獲得超14個贊
換個思路解決,不用多余的各種查詢開銷。在用戶表里面加兩個字段 {連續打卡天數,最后打卡日期}。打卡的時候判斷最后日前是不是今天,如果是啥也不做;如果是昨天,打卡天數++,更新最后打卡日期;如果是前天或更久的日期,將打開天數改為1,更新最后打卡日期

慕容森
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 關注
- 505 瀏覽
添加回答
舉報
0/150
提交
取消