This article mainly introduces php code for retrieving top-level category IDs for unlimited classification. For more information, see a table where ID is the category id and name is the category name, pid is the ID of the upper-level classification.
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 ......