首页 >后端开发 >php教程 >PHP 实现浏览记录并按日期分组

PHP 实现浏览记录并按日期分组

不言
不言原创
2018-04-16 14:12:391403浏览

这篇文章主要介绍的内容是关于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"
 } 
 } 
}


对的,这正是我想要的效果。

相关推荐:

PHP中实现中文字符串反转避免乱码的方法


以上是PHP 实现浏览记录并按日期分组的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn