我有这个数组数据结构:
$records = [];
$records[] = ['id' => 1, 'date' => '2017-03-12', 'operation' => 'sent_email'];
$records[] = ['id' => 1, 'date' => '2017-03-13', 'operation' => 'sent_email'];
$records[] = ['id' => 1, 'date' => '2017-03-13', 'operation' => 'sent_email'];
$records[] = ['id' => 1, 'date' => '2017-03-14', 'operation' => 'forgot_password'];
$records[] = ['id' => 1, 'date' => '2017-03-14', 'operation' => 'sent_email'];
$records[] = ['id' => 2, 'date' => '2017-03-14', 'operation' => 'sent_email'];
$records[] = ['id' => 2, 'date' => '2017-03-14', 'operation' => 'forgot_password'];
$records[] = ['id' => 1, 'date' => '2017-03-27', 'operation' => 'sent_email'];
$records[] = ['id' => 1, 'date' => '2017-03-29', 'operation' => 'sent_email'];
在这个数组中,我存储了网站访问者完成的操作。显然,访问者可以通过 ID 号来识别。
我想做的是统计每个访问者在一周内(包括周一和周日)使用“sent_email”操作的次数。
例如:第一 strip 有'sent_email'操作的记录显示该操作发生在'2017-03-12'(星期日),这意味着对于id = 1的用户,该操作在该周内只发生了一次。
对于 id = 1 的用户,其他接下来的三个“sent_email”操作在另一周内发生了三次。 (2017-03-13、2017-03-13、2017-03-14 这三个日期属于同一周)。
我知道我可能需要遍历每条记录并以某种方式检查这些日期是否属于同一周,但我感到困惑并卡在这里,我不明白完成它所需的逻辑步骤。如果有人能给我一个解释或伪代码,我将非常感激,无论它能帮助我解决这个问题,我真的很喜欢自己解决问题,但因为我被困住了,我只需要有人让我起来,运行。
提前感谢您提供的任何帮助。
最佳答案
DateTime 对象和 strtotime() 函数都理解相对日期字符串,因此您可以做一些简洁的事情,例如“上周二”和“3 天前”。
一些让你入门的伪代码:
// figure out when your monday is
monday = ...
// figure out when your sunday is
sunday = ...
// loop over all records
foreach $record:
// skip records outside the date range you want
if date < monday or date > sunday then skip this record;
// skip records not of the type you want
if operation != email then skip this record;
// register a hit for this user
increment counter for user
关于PHP 计算某个操作每周发生了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916127/