【问题标题】:PHP count how many times a week certain operation occuredPHP计算每周发生多少次特定操作
【发布时间】:2017-03-20 23:59:32
【问题描述】:

我有这个数组数据结构:

$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'];

在这个数组中,我存储了网站访问者完成的操作。显然访客可以通过身份证号码来识别。

我要做的是计算每个访问者在一周内(包括周一和周日)使用“sent_email”操作的次数。

例如:“sent_email”操作的第一条记录显示该操作发生在“2017-03-12”(星期日),这意味着对于 id = 1 的用户,该操作在该周仅发生了一次。

对于 id = 1 的用户,接下来的三个“sent_email”操作在另一周发生了 3 次。 (2017-03-13、2017-03-13、2017-03-14 这三个日期属于同一周)。

我知道我可能需要遍历每条记录并以某种方式检查这些日期是否属于同一周,但我感到困惑并被困在这里,我不明白完成它所需的逻辑步骤。如果有人能给我一个解释或伪代码,我将非常感激,无论是什么可以帮助我解决这个问题的,我真的很喜欢自己解决问题,但是因为我被困住了,我只需要有人让我起来正在运行。

提前感谢您提供的任何帮助。

【问题讨论】:

    标签: php arrays algorithm date comparison


    【解决方案1】:

    DateTime 对象和 strtotime() 函数都理解相对日期字符串,因此您可以执行“last tuesday”和“3 days ago”之类的简洁操作。

    一些伪代码可以帮助您入门:

    // 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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-15
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多