Home > Article > Backend Development > PHP unlimited classification to get the top classification ID
There is such a table, id is the ID of the category, name is the name of the category, and pid is the ID of the upper-level category.
Now there is a category ID, and the program needs to find the superior of its superior's superior...the ID of the category, simply put, is to find the ID of the top category.
For example, the ID of "Fresh Fruit" is 13, and the corresponding parent category ID is 5, and the parent ID of 5 is 1. 1 has no parent category, which is the top category.
In the past, when I was young and ignorant, I always thought of using recursion to search, and then caching the results to solve performance problems.
Later I tried caching the entire table and searching recursively.
Later...it seems that there is less chance of encountering infinite classification...
Recently a colleague asked me how to "elegantly" solve this problem.
So I had an idea and came up with the following solution:
<?php $sql = "select id, pid from tablename "; // 查询后 将结果处理成 如下数组格式 $arr = [ // id => pid 1 => 0, // 省略... 5 => 1, // 省略... 13 => 5 ]; // 建议将这数组缓存起来 $id = 13; while($arr[$id]) { $id = $arr[$id]; } echo $id; // 1
I have to say: it’s so elegant! Even I admired myself, and my colleagues even fell to the ground and cried bitterly.
Because he wrote dozens of lines of code for looping, judging, and recursing, I replaced it with two lines of code...
The above introduces the PHP unlimited classification to obtain the top classification ID, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.