PHP Unlimited comments Nested implementation code PHP tips

Source: Internet
Author: User
This article is about the PHP infinite comment Nested instance introduction, I in the process of design BB, also has been thinking about whether it can not be recursive to achieve infinite classification of the structure and parent-child structure lookup, because if the algorithm is not optimized here the consequences may be fatal

In the process of designing BB, I have also been thinking about whether it is possible to implement infinite classification structure and parent-child structure lookups without recursion, because it can be fatal if the algorithm is not optimized here! Imagine an article if the number of comments is 300, according to the normal recursive algorithm, at least to query the database 301 times, and in the absence of any nesting, if there are one or two levels of nesting or the number of comments over 1000, then the database is not directly down?
In fact, PHP's powerful array processing capabilities have helped us to solve this problem quickly and easily. Classified as an infinite class.

Database structure:

Idparentid NewsID Commts
108 Article ID 8 reviews
21 8 replies to the comment with ID 1
328 replies to the comment with ID 2

To display the comment of article number 8 in the foreground nested, in fact we only use the query database once, namely "SELECT * from TABLE WHERE newsid=8", and the late recursive work to the powerful PHP array to complete. The problem that may be involved here is the reorganization of the structure of the array, and all the comments that stay on the first class classification are placed under their own parentid to form children.
The following will be Bbcomment class in the code paste out, I hope to share with you my ideas, but also hope that we can put forward a better and more efficient algorithm.

Method One

/** * * */function Getcommentsfromarybyid ($commtAry, $id) {if (!is_array ($commtAry)) return FALSE by ID criteria recursively from the comment array;   foreach ($commtAry as $key = + $value) {if ($value [' id '] = = $id) return $value; if (Isset ($value [' Children ']) && Is_array ($children)) $this->getcommentsformarybyid ($value [' Children '],  $ID);  }}/** * Append a sub-comment to the main comment and form the Children subkey * * @param array $commtAry original comment data reference * @param int $parentId main Comment ID * @param array Value of $childrenAry sub-comment */function addchildentocommentsary ($commtAry, $parentId, $childrenAry) {if (!is_array ($commtAry)   ) return FALSE; foreach ($commtAry as $key = + $value) {if ($value [' id '] = = $parentId) {$commtAry [$key] [' children '] [] = $childrenA    Ry   return TRUE; if (Isset ($value [' Children ')) $this->addchildentocommentsary ($commtAry [$key] [' Children '], $parentId, $  Childrenary);   }} $result = $this->bbdm->select ($table, $column, $condition, 0, 1000);  /* Start a nested comment structure reorganization */Array_shift ($result); $count = Count ($result);  $i = 0; while ($i < $count) {if (' 0 '! = $result [$i] [' parentid ']) {$this->addchildentocommentsary ($result, $result [$i    [' ParentID '], $result [$i]);   Unset ($result [$i]);  } $i + +;  } $result = Array_values ($result); /* Reorganization End */

Implementation Method Two

Core code excerpt from WordPress

<?php$comments = array (' id ' = ' 3 ', ' parent ' = ' 0 '), array (' id ' = ' 9 ', ' Parent '  = ' 0 '), array (' id ' = ' 1 ', ' parent ' = ' 3 '), array (' id ' = ' 2 ', ' parent ' = ' 3 '), Array (' id ' = ' 5 ', ' parent ' = ' 1 '), array (' id ' = ' 7 ', ' parent ' = ' 1 ')); function HTML5  _comment ($comment) {echo ' <li> '; echo ' ID: ', $comment [' id '], ' parent: ', $comment [' Parent '];}  Function Start_el (& $output, $comment) {Ob_start ();  Html5_comment ($comment); $output. = Ob_get_clean ();} Function End_el (& $output) {$output. = "</li><!--#comment-##-->\n";} Function Start_lvl (& $output) {$output. = ' <ol class= ' children ' > '. "\ n";} Function End_lvl (& $output) {$output. = "</ol><!--. Children-->\n";}  function Display_element ($e, & $children _elements, $max _depth, $depth, & $output) {$id = $e [' id ']; Start_el ($output, $e); The start code for the current comment if ($max _deptH > $depth +1 && isset ($children _elements[$id])) {//If the maximum layer is not exceeded and there is a child element array foreach ($children _elements[$id] As $child) {if (!isset ($newlevel)) {//The first loop does not set the variable $newlevel, so the $newlevel is set to true, and the start code of the child element is started; the second and subsequent loops have been set $newlevel, The start code for child elements is no longer added.        Because the same batch of loops is the sibling element, only one child element is required to start the code, and the loop content is a side-by-side relationship.        $newlevel = true;      START_LVL ($output); } display_element_template ($child, $children _elements, $max _depth, $depth +1, $output); $child as a parameter, continue to look for subordinate elements} unset ($children _elements[$id]); After the release of the variable, it will not be repeated to determine the value, recursion and continue to determine the remaining child elements} if (Isset ($newlevel) && $newlevel) {//If the child element is found earlier, here is the end code of the child element is executed end_l  VL ($output); } end_el ($output); End code for current Comment}function display_element_template ($e, & $children _elements, $max _depth, $depth, & $output) {$id = $e  [' ID '];  Display_element ($e, $children _elements, $max _depth, $depth, $output); CH ($children_elements[$id] as $child) {display_element_template ($child, $children _elements, $max _depth, $depth, $output); } unset ($children _elements[$id]);  Run out of release variables}}function comments_list ($comments) {$top _level_elements = array ();  $children _elements = Array ();    foreach ($comments as $e) {if (0 = = $e [' parent ']) {$top _level_elements[] = $e;    } else {$children _elements[$e [' parent ']][] = $e;  }} $output = ';  foreach ($top _level_elements as $e) {display_element_template ($e, $children _elements, 2, 0, $output); }//var_dump ($children _elements);//Because the variable is released every time the $children_elements is exhausted, so the last $children_elements is the empty array return $output;} Echo ' <ol class= ' comment-list ' > ', Comments_list ($comments), ' </ol> ';

This article is introduced to this, in fact, we refer to some open-source CMS can also see a lot of good code, I hope we will support the PHP Chinese network.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.