這篇文章主要介紹的內容是關於PHP 實現瀏覽記錄並按日期分組,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
現有測試資料如下,要求實現如中的效果:
array(4) { [0] => array(6) { ["visit_id"] => int(127) ["goods_id"] => int(16) ["visittime"] => int(1494399935) ["goods_name"] => string(53) "OPPO R9s 全網通4G+64G 雙卡雙待手機 玫瑰金" ["shop_price"] => string(6) "500.00" } [1] => array(6) { ["visit_id"] => int(124) ["goods_id"] => int(13) ["visittime"] => int(1494399921) ["goods_name"] => string(76) "SIEMENS/西門子 KA92NV09TI雙開門家用對開門電冰箱變頻旗艦款" ["shop_price"] => string(7) "4000.00" } [2] => array(6) { ["visit_id"] => int(123) ["goods_id"] => int(27) ["visittime"] => int(1494399903) ["goods_name"] => string(85) "愛他美白金版Aptamil 幼兒配方奶粉3段(12-36個月適用)900g(歐洲進口)" ["shop_price"] => string(6) "329.00" } [3] => array(6) { ["visit_id"] => int(120) ["goods_id"] => int(26) ["visittime"] => int(1494224263) ["goods_name"] => string(21) "歡樂穀免票一張" ["shop_price"] => string(5) "50.00" } }
|
還沒實現之前我想這個代碼不知道要O(n)呢還是更高的複雜度才能實現,細想一下,其實php的數組底層就是雜湊實現的,如何簡單利用這個特性使複雜度降到O(1)呢?
show me the code:
/* 瀏覽記錄按日期分組 */function groupVisit($visit) { $curyear = date('Y'); $visit_list = []; foreach ($visit as $v) { if ($curyear == date('Y', $v['visittime'])) { $date = date('m月d日', $v['visittime']); } else { $date = date('Y年m月d日', $v['visittime']); } $visit_list[$date][] = $v; } return $visit_list; }
|
說明:入參 $visit 就是上面一開始的測試資料,函數中還對使用者體驗做了一些最佳化,比如,你的瀏覽記錄中總是顯示出今年的年份,是不是感覺有點冗餘,所以如果是本年份的話,年份就要隱藏起來,其他年份還是照樣顯示出來。不然代碼會更加簡潔。
好了上面的測試資料經過該函數之後,再把傳回值列印出來,有:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
array(2) { ["05月10日"] => array(3) { [0] => array(6) { ["visit_id"] => int(127) ["goods_id"] => int(16) ["visittime"] => int(1494399935) ["goods_name"] => string(53) "OPPO R9s 全網通4G+64G 雙卡雙待手機 玫瑰金" ["shop_price"] => string(6) "500.00" } [1] => array(6) { ["visit_id"] => int(124) ["goods_id"] => int(13) ["visittime"] => int(1494399921) ["goods_name"] => string(76) "SIEMENS/西門子 KA92NV09TI雙開門家用對開門電冰箱變頻旗艦款" ["shop_price"] => string(7) "4000.00" } [2] => array(6) { ["visit_id"] => int(123) ["goods_id"] => int(27) ["visittime"] => int(1494399903) ["goods_name"] => string(85) "愛他美白金版Aptamil 幼兒配方奶粉3段(12-36個月適用)900g(歐洲進口)" ["shop_price"] => string(6) "329.00" } } ["05月08日"] => array(1) { [0] => array(6) { ["visit_id"] => int(120) ["goods_id"] => int(26) ["visittime"] => int(1494224263) ["goods_name"] => string(21) "歡樂穀免票一張" ["shop_price"] => string(5) "50.00" } } }
|
對的,這正是我想要的效果。