2017-03-20 110 views
0

我有這樣的陣列:PHP算一個星期一定的操作多少次發生

$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的用戶。

其他接下來的三個'sent_email'操作,id = 1的用戶在另一週發生了三次。 (2017-03-13,2017-03-13,2017-03-14這三個日期屬於同一周)。

我知道我可能需要遍歷每條記錄,並以某種方式檢查這些日期,如果它們屬於同一周,但我感到困惑並卡在這裏,我不明白完成它所需的邏輯步驟。如果有人能給我一個解釋或僞代碼,無論這會幫助我解決這個問題,我會非常感激,我真的很喜歡自己解決問題,但因爲我卡住了,我只需要有人來幫我解決問題,運行。

非常感謝您提供任何幫助。

回答

2

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