search
Homephp教程php手册php 无限级分类 获取顶级分类ID,php顶级

php 无限级分类 获取顶级分类ID,php顶级

有这样一个表,id是分类的ID,name是分类名称,pid是上级分类的ID。

现在有个分类ID,程序要找到它上级的上级的上级……分类的ID,简单说就是找出顶级分类的ID。
比如“新鲜水果”的ID是13,对应父类ID是5,而5的父ID是1,1没有父类,也就是顶级分类了。

以前年轻气盛不懂事,总想着用递归来查找,然后再将结果缓存来解决性能问题。
后来又试过将整个表缓存起来,再递归查找。
再后来……似乎比较少有机会遇到无限级分类……

最近有个同事问我怎么“优雅”的解决这个问题。
于是我灵机一动,就有了如下解决方案:

<&#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

不得不说:真是太优雅了!连我都佩服我自己了,同事更是五体投地,痛哭流涕。
因为他写了几十行循环再判断再递归的代码,被我用两行代码替换了……

您可能感兴趣的文章:

  • php+mysql实现无限级分类 | 树型显示分类关系
  • php实现无限级分类实现代码(递归方法)
  • php 无限级分类,超级简单的无限级分类,支持输出树状图
  • ThinkPHP无限级分类原理实现留言与回复功能实例
  • php实现无限级分类
  • PHP实现递归无限级分类
  • PHP实现无限级分类(不使用递归)
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use