Home  >  Article  >  Backend Development  >  PHP unlimited classification to get the top category ID, PHP top_PHP tutorial

PHP unlimited classification to get the top category ID, PHP top_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:57:23944browse

php infinite-level classification Get the top-level category ID, php top-level

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:

<&#63;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...

Articles you may be interested in:

  • php mysql implements infinite level classification | tree display classification relationship
  • php implements infinite level classification implementation code (recursive method)
  • php infinite level classification, super simple infinite level classification, supports output tree diagram
  • ThinkPHP infinite level classification principle to implement message and reply function examples
  • php realizes unlimited level classification
  • PHP implements recursive infinite-level classification
  • PHP implements infinite-level classification (without recursion)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1109173.htmlTechArticlephp Infinite-level classification gets the top-level classification ID. There is such a table at the top level of php. The id is the ID of the classification and the name is Category name, pid is the ID of the upper-level category. Now there is a category ID, and the program needs to find it...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn