PHP 中实现浏览记录并按日期分组的实例代码

现有测试数据如下,要求实现如下图中的效果:

  1. array(4) {
  2. [0] =>array(6) {
  3. ["visit_id"] => int(127)
  4. ["goods_id"] => int(16)
  5. ["visittime"] => int(1494399935)
  6. ["goods_name"] => string(53)"OPPO R9s 全网通4G+64G 双卡双待手机 玫瑰金"
  7. ["shop_price"] => string(6)"500.00"
  8. }
  9. [1] =>array(6) {
  10. ["visit_id"] => int(124)
  11. ["goods_id"] => int(13)
  12. ["visittime"] => int(1494399921)
  13. ["goods_name"] => string(76)"SIEMENS/西门子 KA92NV09TI双开门家用对开门电冰箱变频旗舰款"
  14. ["shop_price"] => string(7)"4000.00"
  15. }
  16. [2] =>array(6) {
  17. ["visit_id"] => int(123)
  18. ["goods_id"] => int(27)
  19. ["visittime"] => int(1494399903)
  20. ["goods_name"] => string(85)"爱他美白金版Aptamil 幼儿配方奶粉3段(12-36个月适用)900g(欧洲进口)"
  21. ["shop_price"] => string(6)"329.00"
  22. }
  23. [3] =>array(6) {
  24. ["visit_id"] => int(120)
  25. ["goods_id"] => int(26)
  26. ["visittime"] => int(1494224263)
  27. ["goods_name"] => string(21)"欢乐谷免票一张"
  28. ["shop_price"] => string(5)"50.00"
  29. }
  30. }

还没实现之前我想这个代码不知道要O(n)呢还是更高的复杂度才能实现,细想一下,其实php的数组底层就是哈希实现的,如何简单利用这个特性使复杂度降到O(1)呢?

  1. show me the code:
  2. /* 浏览记录按日期分组 */
  3. functiongroupVisit($visit)
  4. {
  5. $curyear=date('Y');
  6. $visit_list= [];
  7. <a href="/tags.php/foreach/" target="_blank">foreach</a>($visitas$v) {
  8. if($curyear==date('Y',$v['visittime'])) {
  9. $date=date('m月d日',$v['visittime']);
  10. }else{
  11. $date=date('Y年m月d日',$v['visittime']);
  12. }
  13. $visit_list[$date][] =$v;
  14. }
  15. return$visit_list;
  16. }

好了上面的测试数据经过该函数之后,再把返回值打印出来,有:

  1. array(2) {
  2. ["05月10日"] =>array(3) {
  3. [0] =>array(6) {
  4. ["visit_id"] => int(127)
  5. ["goods_id"] => int(16)
  6. ["visittime"] => int(1494399935)
  7. ["goods_name"] => string(53)"OPPO R9s 全网通4G+64G 双卡双待手机 玫瑰金"
  8. ["shop_price"] => string(6)"500.00"
  9. }
  10. [1] =>array(6) {
  11. ["visit_id"] => int(124)
  12. ["goods_id"] => int(13)
  13. ["visittime"] => int(1494399921)
  14. ["goods_name"] => string(76)"SIEMENS/西门子 KA92NV09TI双开门家用对开门电冰箱变频旗舰款"
  15. ["shop_price"] => string(7)"4000.00"
  16. }
  17. [2] =>array(6) {
  18. ["visit_id"] => int(123)
  19. ["goods_id"] => int(27)
  20. ["visittime"] => int(1494399903)
  21. ["goods_name"] => string(85)"爱他美白金版Aptamil 幼儿配方奶粉3段(12-36个月适用)900g(欧洲进口)"
  22. ["shop_price"] => string(6)"329.00"
  23. }
  24. }
  25. ["05月08日"] =>array(1) {
  26. [0] =>array(6) {
  27. ["visit_id"] => int(120)
  28. ["goods_id"] => int(26)
  29. ["visittime"] => int(1494224263)
  30. ["goods_name"] => string(21)"欢乐谷免票一张"
  31. ["shop_price"] => string(5)"50.00"
  32. }
  33. }
  34. }

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

以上所述是小编给大家介绍的PHP 实现浏览记录并按日期分组,希望对大家有所帮助。在此也非常感谢大家对本网站的支持!