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)

Jul 25, 2016 am 09:06 AM

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles