Home >Backend Development >PHP Tutorial >PHP implements a two-way circular queue --- (implementing functions such as forward and backward of historical records)

PHP implements a two-way circular queue --- (implementing functions such as forward and backward of historical records)

WBOY
WBOYOriginal
2016-07-25 09:06:55977browse
To implement a function of recording operation history


  1. A function similar to the undo and anti-undo functions. (Realize forward and backward operations)
  2. Log in to the discuz forum to view the posts (you can go forward and backward to view the posts, and view the post history)
  3. The logic is the same as the forward and backward functions of the Windows Explorer address bar.


Based on this need, a data structure is implemented. I wrote a general class, temporarily called the history class.
[The principle is similar to that of a clock. When instantiating an object, you can construct a ring with a length of N (the length can be determined as needed) nodes]
Then integrate various operations. Forward, backward, insert, modify insert.

The class can construct an array. Or pass in array parameters to construct an object. After each operation, you can get the array after the operation. After the operation data can be saved in a suitable way according to your needs. Put it in a cookie or session, or serialize it, or convert it to json data and save it in the database, or put it in a file. Convenient for next time use.

In order to facilitate expansion, store more data. Specifically, each piece of data is also an array record.
For example, expand as needed: array('path'=>'D:/www/','sss'=>value)

------------------------------------------------ ----------------------------------


By the way, I posted a file for debugging variables that I wrote.

  1. pr() can format and highlight output variables. pr($arr),pr($arr,1) is to exit after output.
  2. debug_out() is used to output multiple variables. The default is to exit.
  3. debug_out($_GET,$_SERVER,$_POST,$arr) ;
  1. include 'debug.php';
  2. /**
  3. * History operation class
  4. * Pass in or construct an array. In the form:
  5. array(
  6. 'history_num'=>20, //Total number of queue nodes
  7. 'first'=>0, //Starting position, starting from 0. Array index value
  8. 'last'=> ;0, //End position, starting from 0.
  9. 'back'=>0, //How many steps back from the first position, the difference.
  10. 'history'=>array( //Array, storing the operation queue .
  11. array('path'=>'D:/'),
  12. array('path'=>'D:/www/'),
  13. array('path'=>'E:/') ,
  14. array('path'=>'/home/')
  15. ……
  16. )
  17. )
  18. */
  19. class history{
  20. var $history_num;
  21. var $first;
  22. var $last;
  23. var $ back;
  24. var $history=array();
  25. function __construct($array=array(),$num=12){
  26. if (!$array) {//The array is empty. Construct a circular queue.
  27. $history=array();
  28. for ($i=0; $i < $num; $i++) {
  29. array_push($history,array('path'=>''));
  30. }
  31. $ array=array(
  32. 'history_num'=>$num,
  33. 'first'=>0,//Starting position
  34. 'last'=>0,//Ending position
  35. 'back'=>0,
  36. 'history'=>$history
  37. );
  38. }
  39. $this->history_num=$array['history_num'];
  40. $this->first=$array['first'];
  41. $this- >last=$array['last'];
  42. $this->back=$array['back'];
  43. $this->history=$array['history'];
  44. }
  45. function nextNum ($i,$n=1){//N values ​​under the loop. Similar to clock loop.
  46. return ($i+$n)<$this->history_num ? ($i+$n):($i+$n-$this->history_num);
  47. }
  48. function prevNum($i,$n= 1){//The last value i on the loop. Go back N positions.
  49. return ($i-$n)>=0 ? ($i-$n) : ($i-$n+$this->history_num);
  50. }
  51. function minus($i,$j){ //The only difference between two clockwise points is i-j
  52. return ($i > $j) ? ($i - $j):($i-$j+$this->history_num);
  53. }
  54. function getHistory (){//Return array, used for saving or serialization operations.
  55. return array(
  56. 'history_num'=> $this->history_num,
  57. 'first' => $this->first,
  58. 'last' => $this->last,
  59. 'back' => $this->back,
  60. 'history' => $this->history
  61. );
  62. }
  63. function add($path){
  64. if ($this->back!=0) {//If there is a back operation record, insert it.
  65. $this->goedit($path);
  66. return;
  67. }
  68. if ($this->history[0]['path']=='') {//Just constructed, no need to add one. First position Not moving forward
  69. $this->history[$this->first]['path']=$path;
  70. return;
  71. }else{
  72. $this->first=$this->nextNum($ this->first);//Move the first position forward
  73. $this->history[$this->first]['path']=$path;
  74. }
  75. if ($this->first==$ this->last) {//The starting position and the ending position meet
  76. $this->last=$this->nextNum($this->last);//The end position moves forward.
  77. }
  78. }
  79. function goback(){//Return the address N steps back from first.
  80. $this->back+=1;
  81. //The maximum number of steps back is the difference from the starting point to the end point (clockwise difference)
  82. $mins=$this->minus($this->first,$this- >last);
  83. if ($this->back >= $mins) {//Back to the last point
  84. $this->back=$mins;
  85. }
  86. $pos=$this-> prevNum($this->first,$this->back);
  87. return $this->history[$pos]['path'];
  88. }
  89. function gonext(){//Back N from first Take one step forward.
  90. $this->back-=1;
  91. if ($this->back<0) {//Return to the last point
  92. $this->back=0;
  93. }
  94. return $this->history [$this->prevNum($this->first,$this->back)]['path'];
  95. }
  96. function goedit($path){//Back to a certain point without moving forward It's a modification.The firs value is the last value.
  97. $pos=$this->minus($this->first,$this->back);
  98. $pos=$this->nextNum($pos);//Next
  99. $this-> ;history[$pos]['path']=$path;
  100. $this->first=$pos;
  101. $this->back=0;
  102. }
  103. //Can I go back
  104. function isback() {
  105. if ($this->back < $this->minus($this->first,$this->last)) {
  106. return ture;
  107. }
  108. return false;
  109. }
  110. // Is it possible to move forward
  111. function isnext(){
  112. if ($this->back>0) {
  113. return true;
  114. }
  115. return false;
  116. }
  117. }
  118. //Test code.
  119. $hi=new history(array(),6);//If an empty array is passed in, the array construction will be initialized.
  120. for ($i=0; $i <8; $i++) {
  121. $hi->add('s'.$i);
  122. }
  123. pr($hi->goback());
  124. pr($hi->goback());
  125. pr($hi->goback());
  126. pr($hi->gonext());
  127. pr($hi->gonext() );
  128. pr($hi->gonext());
  129. pr($hi->gonext());
  130. $hi->add('asdfasdf');
  131. $hi->add(' asdfasdf2');
  132. pr($hi->getHistory());
  133. $ss=new history($hi->getHistory());//Constructed directly with array.
  134. $ss->add('asdfasdf');
  135. $ss->goback();
  136. pr($ss->getHistory());
  137. ?>
Copy code
  1. /**
  2. * Get the name of the variable
  3. * eg hello="123" Get the ss string
  4. */
  5. function get_var_name(&$aVar){
  6. foreach($GLOBALS as $key=>$var)
  7. {
  8. if($aVar== $GLOBALS[$key] && $key!="argc"){
  9. return $key;
  10. }
  11. }
  12. }
  13. /**
  14. * Formatted output variables, or objects
  15. * @param mixed $var
  16. * @param boolean $exit
  17. */
  18. function pr($var,$exit = false){
  19. ob_start();
  20. $style='';
  21. if (is_array($ var)){
  22. print_r($var);
  23. }
  24. else if(is_object($var)){
  25. echo get_class($var)." Object";
  26. }
  27. else if(is_resource($var)){
  28. echo (string)$var;
  29. }
  30. else{
  31. echo var_dump($var);
  32. }
  33. $out = ob_get_clean();//Buffer output to $out variable
  34. $out=preg_replace('/"(. *)"/','"'.'\1'.'"',$out);//Highlight string variable
  35. $out=preg_replace ('/=>(.*)/','=>'.''.'\1'.'',$out);/ /Highlight=>The following value
  36. $out=preg_replace('/[(.*)]/','['.'\1'.']',$out);//Highlight variable
  37. $from = array( ' ','(',')','=>');
  38. $to = array(' ','(',')','=>');
  39. $out=str_replace($from,$to,$ out);
  40. $keywords=array('Array','int','string','class','object','null');//Keyword highlighting
  41. $keywords_to=$keywords;
  42. foreach ($keywords as $key=>$val)
  43. {
  44. $keywords_to[$key] = ''.$val.'';
  45. }
  46. $ out=str_replace($keywords,$keywords_to,$out);
  47. echo $style.'
    <b id="debug_keywords">'.get_var_name($var).'&lt ;/b> = '.$out.'
    ';
  48. if ($exit) exit;//Exit if true
  49. }
  50. /**
  51. * Debug output variables, object values.
  52. * Any number of parameters (variables of any type)
  53. * @return echo
  54. */
  55. function debug_out(){
  56. $avg_num = func_num_args();
  57. $avg_list= func_get_args();
  58. ob_start();
  59. for($i=0; $i < $avg_num; $i++) {
  60. pr($avg_list[$i]) ;
  61. }
  62. $out=ob_get_clean();
  63. echo $out;
  64. exit;
  65. }
  66. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn