這篇文章主要介紹的內容是關於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 是上面一開始的測試數據,函數中也對使用者體驗做了一些最佳化,例如,你的瀏覽記錄總是顯示出今年的年份,是不是感覺有點冗餘,所以如果是本年份的話,年份就要隱藏起來,其他年份還是照樣顯示出來。不然程式碼會更簡潔。
好了上面的測試資料經過該函數之後,再把回傳值印出來,有:
##8 9 10111213#14#15#16# 17181920#21 |
#22
##24 |
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" } } }##################################################################### #########################對的,這正是我想要的效果。 ######相關推薦:#########PHP中實作中文字串反轉避免亂碼的方法##############
以上是PHP 實作瀏覽記錄並按日期分組的詳細內容。更多資訊請關注PHP中文網其他相關文章!