has such a table, id is the ID of the category, name is the category name, and pid is the ID of the upper-level category.
Now there is a category ID, and the program needs to find its superior’s superior’s superior...the category ID. Simply put, it 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...
A colleague recently asked me how to solve this problem “elegantly”.
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 that looped, judged, and recursed, I replaced it with two lines of code...