찾다
백엔드 개발PHP 튜토리얼PHP实现无限极归类

PHP实现无限极分类

利用两个for循环实现无限级分类

表:

字段名 字段类型 备注 默认值
id int 主键 auto-increment
name varchar 分类名称
pid int 父类id 0

顶级分类的 pid 默认就是0了。当我们想取出某个分类的子分类树的时候,基本思路就是递归,当然,出于效率问题不建议每次递归都查询数据库,通常的做法是先将所有分类取出来,数据保存到PHP数组里,再进行处理,最后还可以将结果缓存起来以提高下次请求的效率。

先来构建一个原始数组,这个直接从数据库中查询出来就行:

1. 构建数据

<code class=" hljs php"><span class="hljs-variable">$categories</span> = <span class="hljs-keyword">array</span>(    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">1</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'电脑'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">0</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">2</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'手机'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">0</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">3</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'笔记本'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">1</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">4</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'台式机'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">1</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">5</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'智能机'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">2</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">6</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'功能机'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">2</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">7</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'超级本'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">3</span>),    <span class="hljs-keyword">array</span>(<span class="hljs-string">'id'</span>=><span class="hljs-number">8</span>,<span class="hljs-string">'name'</span>=><span class="hljs-string">'游戏本'</span>,<span class="hljs-string">'pid'</span>=><span class="hljs-number">3</span>),);</code>

目标是将它转化为下面这种结构
电脑 >笔记本 >>超级本 >> 游戏本 > 台式机
手机 > 智能机 > 功能机

用数组来表示的话,可以增加一个 children 键来存储它的子分类

<code class=" hljs php"><span class="hljs-keyword">array</span>(    <span class="hljs-comment">//1对应$categories中的id ,方便直接读取</span>    <span class="hljs-number">1</span> => <span class="hljs-keyword">array</span>(        <span class="hljs-string">'id'</span>=><span class="hljs-number">1</span>,        <span class="hljs-string">'name'</span>=><span class="hljs-string">'电脑'</span>,        <span class="hljs-string">'pid'</span>=><span class="hljs-number">0</span>,        children=><span class="hljs-keyword">array</span>(            &<span class="hljs-keyword">array</span>(                <span class="hljs-string">'id'</span>=><span class="hljs-number">3</span>,                <span class="hljs-string">'name'</span>=><span class="hljs-string">'笔记本'</span>,                <span class="hljs-string">'pid'</span>=><span class="hljs-number">1</span>,                <span class="hljs-string">'children'</span>=><span class="hljs-keyword">array</span>(                    <span class="hljs-comment">//此处省略</span>                )            ),            &<span class="hljs-keyword">array</span>(                <span class="hljs-string">'id'</span>=><span class="hljs-number">4</span>,                <span class="hljs-string">'name'</span>=><span class="hljs-string">'台式机'</span>,                <span class="hljs-string">'pid'</span>=><span class="hljs-number">1</span>,                <span class="hljs-string">'children'</span>=><span class="hljs-keyword">array</span>(                    <span class="hljs-comment">//此处省略</span>                )            ),        )    ),    <span class="hljs-comment">//其他分类省略</span>)</code>

2. 处理过程:

<code class=" hljs php"><span class="hljs-variable">$tree</span> = <span class="hljs-keyword">array</span>();<span class="hljs-comment">//第一步,将所有的分类id作为数组key,并创建children单元</span><span class="hljs-keyword">foreach</span>(<span class="hljs-variable">$categories</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$category</span>){    <span class="hljs-variable">$tree</span>[<span class="hljs-variable">$category</span>[<span class="hljs-string">'id'</span>]] = <span class="hljs-variable">$category</span>;    <span class="hljs-variable">$tree</span>[<span class="hljs-variable">$category</span>[<span class="hljs-string">'id'</span>]][<span class="hljs-string">'children'</span>] = <span class="hljs-keyword">array</span>();}<span class="hljs-comment">//第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。</span><span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$tree</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$key</span>=><span class="hljs-variable">$value</span>) {    <span class="hljs-keyword">if</span> (<span class="hljs-variable">$value</span>[<span class="hljs-string">'pid'</span>] != <span class="hljs-number">0</span>) {        <span class="hljs-variable">$tree</span>[<span class="hljs-variable">$value</span>[<span class="hljs-string">'pid'</span>]][<span class="hljs-string">'children'</span>][] = &<span class="hljs-variable">$tree</span>[<span class="hljs-variable">$key</span>];    }}print_r(<span class="hljs-variable">$tree</span>);</code>
<code>注:必须通过引用, 否则不会一次遍历就生成最终的结果.</code>

3. 打印结果如下:

<code class=" hljs php"><span class="hljs-keyword">Array</span>(    [<span class="hljs-number">1</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">1</span>            [name] => 电脑            [pid] => <span class="hljs-number">0</span>            [children] => <span class="hljs-keyword">Array</span>                (                    [<span class="hljs-number">0</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">3</span>                            [name] => 笔记本                            [pid] => <span class="hljs-number">1</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                    [<span class="hljs-number">0</span>] => <span class="hljs-keyword">Array</span>                                        (                                            [id] => <span class="hljs-number">7</span>                                            [name] => 超级本                                            [pid] => <span class="hljs-number">3</span>                                            [children] => <span class="hljs-keyword">Array</span>                                                (                                                )                                        )                                    [<span class="hljs-number">1</span>] => <span class="hljs-keyword">Array</span>                                        (                                            [id] => <span class="hljs-number">8</span>                                            [name] => 游戏本                                            [pid] => <span class="hljs-number">3</span>                                            [children] => <span class="hljs-keyword">Array</span>                                                (                                                )                                        )                                )                        )                    [<span class="hljs-number">1</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">4</span>                            [name] => 台式机                            [pid] => <span class="hljs-number">1</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                )                        )                )        )    [<span class="hljs-number">2</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">2</span>            [name] => 手机            [pid] => <span class="hljs-number">0</span>            [children] => <span class="hljs-keyword">Array</span>                (                    [<span class="hljs-number">0</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">5</span>                            [name] => 智能机                            [pid] => <span class="hljs-number">2</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                )                        )                    [<span class="hljs-number">1</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">6</span>                            [name] => 功能机                            [pid] => <span class="hljs-number">2</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                )                        )                )        )    [<span class="hljs-number">3</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">3</span>            [name] => 笔记本            [pid] => <span class="hljs-number">1</span>            [children] => <span class="hljs-keyword">Array</span>                (                    [<span class="hljs-number">0</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">7</span>                            [name] => 超级本                            [pid] => <span class="hljs-number">3</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                )                        )                    [<span class="hljs-number">1</span>] => <span class="hljs-keyword">Array</span>                        (                            [id] => <span class="hljs-number">8</span>                            [name] => 游戏本                            [pid] => <span class="hljs-number">3</span>                            [children] => <span class="hljs-keyword">Array</span>                                (                                )                        )                )        )    [<span class="hljs-number">4</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">4</span>            [name] => 台式机            [pid] => <span class="hljs-number">1</span>            [children] => <span class="hljs-keyword">Array</span>                (                )        )    [<span class="hljs-number">5</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">5</span>            [name] => 智能机            [pid] => <span class="hljs-number">2</span>            [children] => <span class="hljs-keyword">Array</span>                (                )        )    [<span class="hljs-number">6</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">6</span>            [name] => 功能机            [pid] => <span class="hljs-number">2</span>            [children] => <span class="hljs-keyword">Array</span>                (                )        )    [<span class="hljs-number">7</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">7</span>            [name] => 超级本            [pid] => <span class="hljs-number">3</span>            [children] => <span class="hljs-keyword">Array</span>                (                )        )    [<span class="hljs-number">8</span>] => <span class="hljs-keyword">Array</span>        (            [id] => <span class="hljs-number">8</span>            [name] => 游戏本            [pid] => <span class="hljs-number">3</span>            [children] => <span class="hljs-keyword">Array</span>                (                )        ))</code>

优点:关系清楚,修改上下级关系简单。

缺点:使用PHP处理,如果分类数量庞大,效率也会降低。

原文 http://blog.csdn.net/u013927110/article/details/44086253

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
华为GT3 Pro和GT4的差异是什么?华为GT3 Pro和GT4的差异是什么?Dec 29, 2023 pm 02:27 PM

许多用户在选择智能手表的时候都会选择的华为的品牌,其中华为GT3pro和GT4都是非常热门的选择,不少用户都很好奇华为GT3pro和GT4有什么区别,下面就就给大家介绍一下二者。华为GT3pro和GT4有什么区别一、外观GT4:46mm和41mm,材质是玻璃表镜+不锈钢机身+高分纤维后壳。GT3pro:46.6mm和42.9mm,材质是蓝宝石玻璃表镜+钛金属机身/陶瓷机身+陶瓷后壳二、健康GT4:采用最新的华为Truseen5.5+算法,结果会更加的精准。GT3pro:多了ECG心电图和血管及安

修复:截图工具在 Windows 11 中不起作用修复:截图工具在 Windows 11 中不起作用Aug 24, 2023 am 09:48 AM

为什么截图工具在Windows11上不起作用了解问题的根本原因有助于找到正确的解决方案。以下是截图工具可能无法正常工作的主要原因:对焦助手已打开:这可以防止截图工具打开。应用程序损坏:如果截图工具在启动时崩溃,则可能已损坏。过时的图形驱动程序:不兼容的驱动程序可能会干扰截图工具。来自其他应用程序的干扰:其他正在运行的应用程序可能与截图工具冲突。证书已过期:升级过程中的错误可能会导致此issu简单的解决方案这些适合大多数用户,不需要任何特殊的技术知识。1.更新窗口和Microsoft应用商店应用程

如何修复无法连接到iPhone上的App Store错误如何修复无法连接到iPhone上的App Store错误Jul 29, 2023 am 08:22 AM

第1部分:初始故障排除步骤检查苹果的系统状态:在深入研究复杂的解决方案之前,让我们从基础知识开始。问题可能不在于您的设备;苹果的服务器可能会关闭。访问Apple的系统状态页面,查看AppStore是否正常工作。如果有问题,您所能做的就是等待Apple修复它。检查您的互联网连接:确保您拥有稳定的互联网连接,因为“无法连接到AppStore”问题有时可归因于连接不良。尝试在Wi-Fi和移动数据之间切换或重置网络设置(“常规”>“重置”>“重置网络设置”>设置)。更新您的iOS版本:

使用C#中的Array.Sort函数对数组进行排序使用C#中的Array.Sort函数对数组进行排序Nov 18, 2023 am 10:37 AM

标题:C#中使用Array.Sort函数对数组进行排序的示例正文:在C#中,数组是一种常用的数据结构,经常需要对数组进行排序操作。C#提供了Array类,其中有Sort方法可以方便地对数组进行排序。本文将演示如何使用C#中的Array.Sort函数对数组进行排序,并提供具体的代码示例。首先,我们需要了解一下Array.Sort函数的基本用法。Array.So

Win7任务管理器pid怎么显示出来 小编教你怎么显示出来Win7任务管理器pid怎么显示出来 小编教你怎么显示出来Jan 11, 2024 pm 07:00 PM

很多朋友可能对于pid标识符还比较陌生,可以在任务管理器里进行查看。但是有些用户打开任务管理器时找不到PID标识符,其实如果用户想查看进程PID标识符的话,需通过对“任务管理器”相关设置就可以看到了,下面小编就以win7系统为例查看进程PID标识符的方法。PID标志符是windows操作系统对运行的程序的自动分配的一个独一无二的顺序编号,进程中止后PID被系统回收,可能会被继续分配给新运行的程序,当用户需要查看进程的时候都会通过任务管理器进行查看,那么要如何查看进程PID标识符呢?下面就跟大家分

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code<form name="myform"

简单明了的PHP array_merge_recursive()函数使用方法简单明了的PHP array_merge_recursive()函数使用方法Jun 27, 2023 pm 01:48 PM

在进行PHP编程时,我们常常需要对数组进行合并。PHP提供了array_merge()函数来完成数组合并的工作,不过当数组中存在相同的键时,该函数会覆盖原有的值。为了解决这个问题,PHP在语言中还提供了一个array_merge_recursive()函数,该函数可以合并数组并保留相同键的值,使得程序的设计变得更加灵活。array_merge

BubblePal AI companion toy for kids launches with eerily similar concept to sci-fi flick M3GAN <sup style=\"font-size:0.5em;color:#999\" title=\"BubblePal AI companion toy for kids lBubblePal AI companion toy for kids launches with eerily similar concept to sci-fi flick M3GAN <sup style=\"font-size:0.5em;color:#999\" title=\"BubblePal AI companion toy for kids lAug 15, 2024 pm 12:53 PM

BubblePal, a newly launched AI-based interactive toy, appears to be something that could have inspired the writers of the 2022 sci-fi/horror flick M3GAN, if it hadn’t just been launched last week. Based on large language model (LLM) technology, the ‘

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)