Obtain the top-level category ID for php unlimited classification, top-level php Classification
There is a table where id is the category ID, name is the category name, and pid is the ID of the parent category.
Now there is a classification ID, and the program needs to find its superior ...... The category ID, in short, is to find the ID of the top-level category.
For example, the ID of "Fresh Fruit" is 13, and the corresponding parent class ID is 5, while the parent ID of 5 is without a parent class, that is, top-level classification.
In the past, I was so angry that I was not sensible. I always wanted to use recursion to search for the results and then cache the results to solve performance problems.
Later, I tried to cache the entire table and perform recursive search.
Then ...... It seems that there are few opportunities for unlimited classification ......
Recently, a colleague asked me how to solve this problem elegantly.
As a result, I had the following solutions:
<? Php $ SQL = "select id, pid from tablename"; // the query results are processed into the following array format $ arr = [// id => pid 1 => 0, // omit... 5 => 1, // omitted... 13 => 5]; // We recommend caching the array $ id = 13; while ($ arr [$ id]) {$ id = $ arr [$ id];} echo $ id; // 1
I have to say: It's so elegant! Even though I admire myself, my colleagues are even more desperate.
Because he wrote dozens of lines of loop code and then judged to be recursive, I replaced it with two lines of code ......
Articles you may be interested in:
- Php + mysql implement unlimited classification | tree-based display of classification relationships
- Php implementation code for unlimited classification (recursive method)
- Php unlimited classification, super simple unlimited classification, support output tree chart
- ThinkPHP unlimited classification principle to implement the message and reply function instance
- Php achieves unlimited Classification
- PHP implements recursive unlimited Classification
- PHP achieves unlimited classification (no recursion is used)