During the design of BB, I have been thinking about whether it is possible to display the structure of an infinite classification and search for the parent and child structures without recursion, if the algorithm here is not optimized, the consequences may be fatal! Think about it. If the number of comments in an article is 300, you have to query the database for at least 301 times based on the normal recursive algorithm, and the database is still not nested, if there are one or two levels of nesting or over 1000 comments, isn't the database directly down?
In fact, PHP's powerful array processing capabilities can help us solve this problem quickly and conveniently. The following figure shows an infinitely classified
Database structure:
IDparentID newsID commts
108 comments with Article ID 8
21 8 reply to a comment with ID 1
328 reply to a comment with ID 2
To present the comment of Article 8 in the nested form at the front end, we only query the database once, that is, "SELECT * from table where newsID = 8 ", the post-recursion work is handed over to a powerful PHP array. The possible problem here is the reorganization of the structure relationship of the array. All comments staying on the first-level classification will be placed under their parentID to form the children item.
Next we will paste the code in the BBComment class. I hope to share with you my ideas and propose better and more efficient algorithms.
The code is as follows: |
Copy code |
/** * Recursive search by ID from the comment array * */ Function getCommentsFromAryById ($ commtAry, $ id) { If (! Is_array ($ commtAry) return FALSE; Foreach ($ commtAry as $ key => $ value ){ If ($ value ['id'] ==$ id) return $ value; If (isset ($ value ['Children ']) & is_array ($ children) $ this-> getCommentsFormAryById ($ value ['Children'], $ id ); } } /** * Append the subcomment to the primary comment and form the children subitem. * * @ Param array $ commtAry original comment Data Reference * @ Param int $ parentId primary comment ID * @ Param array $ value of the childrenAry subcomment */ Function addChildenToCommentsAry ($ commtAry, $ parentId, $ childrenAry) { If (! Is_array ($ commtAry) return FALSE; Foreach ($ commtAry as $ key => $ value ){ If ($ value ['id'] ==$ parentId ){ $ CommtAry [$ key] ['Children '] [] = $ childrenAry; Return TRUE; } If (isset ($ value ['Children ']) $ this-> addChildenToCommentsAry ($ commtAry [$ key] ['Children'], $ parentId, $ childrenAry ); } } $ Result = $ this-> BBDM-> select ($ table, $ column, $ condition, 0, 1000 ); /* Start to reorganize the nested comment structure */ 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 ); /* Restructuring ended */
|