history_helper.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 2016/10/16
  6. * Time: 下午2:24
  7. */
  8. function comp_history($left,$right)
  9. {
  10. $t_l = intval($left['add_time']);
  11. $t_r = intval($right['add_time']);
  12. if($t_l > $t_r) {
  13. return -1;
  14. }
  15. elseif($t_l == $t_r)
  16. {
  17. $c_l = intval($left['count']);
  18. $c_r = intval($right['count']);
  19. if($c_l > $c_r) {
  20. return 1;
  21. }
  22. elseif($c_l == $c_r) {
  23. return 0;
  24. }
  25. else {
  26. return -1;
  27. }
  28. }
  29. else {
  30. return 1;
  31. }
  32. }
  33. class history_helper
  34. {
  35. private $mContainer;
  36. public function __construct()
  37. {
  38. if(isset($_SESSION['search_history'])) {
  39. $histories = $_SESSION['search_history'];
  40. } else {
  41. $histories = [];
  42. }
  43. $this->mContainer = [];
  44. foreach ($histories as $value)
  45. {
  46. $keyword = $value['keyword'];
  47. $this->mContainer[$keyword] = $value;
  48. }
  49. }
  50. public function __destruct()
  51. {
  52. $history = [];
  53. foreach ($this->mContainer as $key => $value) {
  54. $history[] = $value;
  55. }
  56. $_SESSION['search_history'] = $history;
  57. }
  58. public function add_word($keyword)
  59. {
  60. if(empty($keyword)) {
  61. return false;
  62. }
  63. if(isset($this->mContainer[$keyword])) {
  64. $this->mContainer[$keyword]['add_time'] = time();
  65. $this->mContainer[$keyword]['count'] += 1;
  66. } else {
  67. $this->mContainer[$keyword]['add_time'] = time();
  68. $this->mContainer[$keyword]['count'] = 1;
  69. $this->mContainer[$keyword]['keyword'] = $keyword;
  70. }
  71. uasort($this->mContainer,'comp_history');
  72. return true;
  73. }
  74. public function histories()
  75. {
  76. $pos = 0;
  77. $result = [];
  78. foreach ($this->mContainer as $key => $value)
  79. {
  80. $result[] = $value['keyword'];
  81. if($pos > 10) {
  82. break;
  83. }
  84. ++$pos;
  85. }
  86. return $result;
  87. }
  88. }