現有測試數據如下,要求實現如下圖中的效果:
代碼如下復制代碼
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:
/* 浏覽記錄按日期分組 */
functiongroupVisit($visit)
{
$curyear=date('Y');
$visit_list= [];
foreach($visitas$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 就是上面一開始的測試數據,函數中還對用戶體驗做了一些優化,比如,你的浏覽記錄中總是顯示出今年的年份,是不是感覺有點冗余,所以如果是本年份的話,年份就要隱藏起來,其他年份還是照樣顯示出來。不然代碼會更加簡潔。
好了上面的測試數據經過該函數之後,再把返回值打印出來,有:
代碼如下復制代碼
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 實現浏覽記錄並按日期分組,希望對大家有所幫助。在此也非常感謝大家對本網站的支持!