PHP Unlimited class get top class category id,php top
There is such a table, the ID is the classification of the Id,name is the classification name, PID is the ID of the parent category.
Now there is a classification ID, the program to find its superior superiors ... The ID of the classification is simply to find the ID of the top-level category.
For example, "Fresh fruit" ID is 13, corresponding to the parent class ID is 5, and 5 of the parent ID is no parent class, that is, top-level classification.
Previously young and not sensible, always want to return to find, and then cache the results to solve performance problems.
Later, I tried to cache the entire table, and then recursively look it up.
And then ... There seems to be less chance of encountering an infinite class classification ...
Recently a colleague asked me how to solve this problem "gracefully".
So I brainwave, there is the following solution:
<?php$sql = "SELECT ID, PID from tablename";//query results are processed into the following array format $arr = [ //id = pid 1 = 0, //omitted. .. 5 = 1, //omitted ... The 5];//recommended to cache this array $id = 13;while ($arr [$id]) { $id = $arr [$id];} echo $id; 1
I have to say: it's so elegant! Even I admire myself, colleagues are pleasantly surprised, tears.
Because he wrote dozens of lines of loops and then judged the recursive code, I replaced it with two lines of code ...
Articles you may be interested in:
- PHP+MYSQL enables unlimited class classification | Tree-type display classification relationships
- PHP implements infinite class classification implementation code (recursive method)
- PHP Infinite class classification, Super Simple Infinite class classification, support output tree chart
- thinkphp Infinite Classification principle to implement message and reply function example
- Unlimited class classification for PHP
- Recursive infinite class classification for PHP
- PHP implements an infinite class classification (without using recursion)
http://www.bkjia.com/PHPjc/1109173.html www.bkjia.com true http://www.bkjia.com/PHPjc/1109173.html techarticle PHP Unlimited class get top class classification id,php top has such a table, ID is classified id,name is the classification name, PID is the ID of the parent category. Now there is a category ID, the program to find it ...