在簡單的簽到記錄表中,如何快速計算您已經連續簽到幾天?
假如你已經拿到了所有的簽到記錄日期類似於
<?php $list = [ '2022-08-21', '2022-08-20', '2022-08-19', '2022-08-12' ];
該如何判斷呢?
寫個函數
<?php function calc_num(array $list = []) { if (empty($list)) { return 0; } $num = 1; $today = date('Y-m-d'); $flag = 0; if (!in_array($today, $list)) { array_unshift($list, $today); $flag = -1; } $count = count($list); for ($i = 1; $i < $count; $i++) { if (strtotime($list[$i - 1]) - strtotime($list[$i]) != 86400) { break; } $num++; } return $num + $flag; }
傳入簽到的記錄日期數組,得到計算結果您已經連續簽到xx天.
這裏需要明確一點,如果昨天今天都沒有簽到 則設定爲0.
昨天沒簽到今天簽到了,就是連續1天.
昨天簽到了今天沒簽到,也是連續1天.
昨天簽到了今天也簽到,就是連續2天.
前天簽到了昨天簽到了,今天沒簽到,就是連續2天.
前天簽到了昨天簽到了,今天也簽到,就是連續3天.
所以應該把今天也算在內.最後看今天有沒有簽到如果沒有則減1
或者採用另外一種算法
先判斷昨天和今天是不是簽到了, 如果都沒有則立即返回0
<?php function calc_num2(array $list = []) { if (empty($list)) { return 0; } $diff = strtotime(date('Y-m-d')) - strtotime($list[0]); if ($diff != 0 && $diff != 86400) { return 0;//昨天和今天都沒簽到 則返回0 } $num = 1; $count = count($list); for ($i = 1; $i < $count; $i++) { if (strtotime($list[$i - 1]) - strtotime($list[$i]) != 86400) { break; } $num++; } return $num; }
這個寫法稍微好理解點後面就是計算連續的次數自增就行