Table of Contents
PHP实现无限级分类(不使用递归),php递归
Home php教程 php手册 PHP实现无限级分类(不使用递归),php递归

PHP实现无限级分类(不使用递归),php递归

Jun 13, 2016 am 08:52 AM
php Classification recursion

PHP实现无限级分类(不使用递归),php递归

无限级分类在开发中经常使用,例如:部门结构、文章分类。无限级分类的难点在于“输出”和“查询”,例如

  • 将文章分类输出为
      列表形式;
  • 查找分类A下面所有分类包含的文章。

1.实现原理
几种常见的实现方法,各有利弊。其中“改进前序遍历树”数据结构,便于输出和查询,但是在移动分类和常规理解上有些复杂。

2.数据结构

<&#63;php
 $list = array(
 array('id'=>1, 'fid'=>0, 'title' => '中国'), 
 array('id'=>2, 'fid'=>1, 'title' => '江苏'),
 array('id'=>3, 'fid'=>1, 'title' => '安徽'),
 array('id'=>4, 'fid'=>8, 'title' => '江阴'),
 array('id'=>5, 'fid'=>3, 'title' => '芜湖'),
 array('id'=>6, 'fid'=>3, 'title' => '合肥'),
 array('id'=>7, 'fid'=>3, 'title' => '蚌埠'),
 array('id'=>8, 'fid'=>8, 'title' => '无锡')
 );
&#63;>
Copy after login

各分类之间通过父类id(即fid)进行级别“串联”,形成一棵分类树。在进行串联时候有一点值得注意:分类A的fid不可以是其子类的id。

在使用这种数据结构进行输出时最常用的算法就是“递归”,熟悉PHP语言的朋友肯定知道,PHP不擅长递归 ,而且递归次数有限(100次左右,因操作系统和配置而异)。

由于所有的递归均可以使用循环实现,本文根据PHP语言特点编写了一套关于“无限级”分类的函数,相比递归实现而言效率更高。

3.输出ul列表形式
将上述数据输出为下面的HTML

<ul>
 <li class="first-child">
 <div>江苏</div>
 <ul>
 <li class="first-child last-child">
 <div>无锡</div>
 <ul>
 <li class="first-child last-child">
 <div>江阴</div>
 </li>
 </ul>
 </li>
 </ul>
 </li>
 <li class="last-child">
 <div>安徽</div>
 <ul>
 <li class="first-child"><div>芜湖</div></li>
 <li><div>合肥</div></li>
 <li class="last-child"><div>蚌埠</div></li>
 </ul>
 </li>
</ul>
Copy after login

这种HTML结构在前端使用(使用JavaScript和CSS构造可折叠树)十分方便。具体实现程序如下:

<ul><&#63;php echo get_tree_ul($list, 1); &#63;></ul>
Copy after login

4.输出option列表形式

<select>
 <option value="2">江苏</option>
 <option value="8">    无锡</option>
 <option value="4">        江阴</option>
 <option value="3">安徽</option>
 <option value="5">    芜湖</option>
 <option value="6">    合肥</option>
 <option value="7">    蚌埠</option>
</select>
Copy after login

具体实现程序如下:

<select>
<&#63;php
 // get_tree_option()返回数组,并为每个元素增加了“深度”(即depth)列,直接输出即可
 $options = get_tree_option($list, 1); 
 foreach($options as $op) {
 echo '<option value="' . $op['id'] .'">' . str_repeat(" ", $op['depth'] * 4) . $op['title'] . '<;/option>';
 }
&#63;>
<;/select>
Copy after login

5. 查找某一分类的所有子类

<&#63;php
 $children = get_tree_child($list, 0);
 echo implode(',', $children); // 输出:1,3,2,7,6,5,8,4
&#63;>
Copy after login

6. 查找某一分类的所有父类

<&#63;php
 $children = get_tree_parent($list, 4);
 echo implode(',', $children); //8, 2, 10
&#63;>
Copy after login

7. 相关函数

<&#63;php
function get_tree_child($data, $fid) {
 $result = array();
 $fids = array($fid);
 do {
 $cids = array();
 $flag = false;
 foreach($fids as $fid) {
 for($i = count($data) - 1; $i >=0 ; $i--) {
 $node = $data[$i];
 if($node['fid'] == $fid) {
 array_splice($data, $i , 1);
 $result[] = $node['id'];
 $cids[] = $node['id'];
 $flag = true;
 }
 }
 }
 $fids = $cids;
 } while($flag === true);
 return $result;
}

function get_tree_parent($data, $id) {
 $result = array();
 $obj = array();
 foreach($data as $node) {
 $obj[$node['id']] = $node;
 } 

 $value = isset($obj[$id]) &#63; $obj[$id] : null; 
 while($value) {
 $id = null;
 foreach($data as $node) {
 if($node['id'] == $value['fid']) {
 $id = $node['id'];
 $result[] = $node['id'];
 break;
 }
 }
 if($id === null) {
 $result[] = $value['fid'];
 }
 $value = isset($obj[$id]) &#63; $obj[$id] : null;
 }
 unset($obj);
 return $result;
}

function get_tree_ul($data, $fid) {
 $stack = array($fid);
 $child = array();
 $added_left = array();
 $added_right= array();
 $html_left = array();
 $html_right = array();
 $obj = array();
 $loop = 0;
 foreach($data as $node) {
 $pid = $node['fid'];
 if(!isset($child[$pid])) {
 $child[$pid] = array();
 }
 array_push($child[$pid], $node['id']);
 $obj[$node['id']] = $node;
 }

 while (count($stack) > 0) { 
 $id = $stack[0];
 $flag = false;
 $node = isset($obj[$id]) &#63; $obj[$id] : null;
 if (isset($child[$id])) {
 $cids = $child[$id];
 $length = count($cids);
 for($i = $length - 1; $i >= 0; $i--) {
 array_unshift($stack, $cids[$i]);
 }
 $obj[$cids[$length - 1]]['isLastChild'] = true;
 $obj[$cids[0]]['isFirstChild'] = true;
 $flag = true;
 }
 if ($id != $fid && $node && !isset($added_left[$id])) {
 if(isset($node['isFirstChild']) && isset($node['isLastChild'])) {
 $html_left[] = '<li class="first-child last-child">';
 } else if(isset($node['isFirstChild'])) {
 $html_left[] = '<li class="first-child">';
 } else if(isset($node['isLastChild'])) {
 $html_left[] = '<li class="last-child">';
 } else {
 $html_left[] = '<li>';
 } 
 $html_left[] = ($flag === true) &#63; "<div>{$node['title']}</div><ul>" : "<div>{$node['title']}</div>";
 $added_left[$id] = true;
 } 
 if ($id != $fid && $node && !isset($added_right[$id])) {
 $html_right[] = ($flag === true) &#63; '</ul></li>' : '</li>';
 $added_right[$id] = true;
 }

 if ($flag == false) {
 if($node) {
 $cids = $child[$node['fid']];
 for ($i = count($cids) - 1; $i >= 0; $i--) {
 if ($cids[$i] == $id) {
 array_splice($child[$node['fid']], $i, 1);
 break;
 }
 } 
 if(count($child[$node['fid']]) == 0) {
 $child[$node['fid']] = null;
 }
 }
 array_push($html_left, array_pop($html_right));
 array_shift($stack);
 }
 $loop++;
 if($loop > 5000) return $html_left;
 }
 unset($child);
 unset($obj);
 return implode('', $html_left);
}

function get_tree_option($data, $fid) {
 $stack = array($fid);
 $child = array();
 $added = array();
 $options = array();
 $obj = array();
 $loop = 0;
 $depth = -1;
 foreach($data as $node) {
 $pid = $node['fid'];
 if(!isset($child[$pid])) {
 $child[$pid] = array();
 }
 array_push($child[$pid], $node['id']);
 $obj[$node['id']] = $node;
 }

 while (count($stack) > 0) { 
 $id = $stack[0];
 $flag = false;
 $node = isset($obj[$id]) &#63; $obj[$id] : null;
 if (isset($child[$id])) {
 for($i = count($child[$id]) - 1; $i >= 0; $i--) {
 array_unshift($stack, $child[$id][$i]);
 }
 $flag = true;
 }
 if ($id != $fid && $node && !isset($added[$id])) {
 $node['depth'] = $depth;
 $options[] = $node;
 $added[$id] = true;
 }
 if($flag == true){
 $depth++;
 } else {
 if($node) {
 for ($i = count($child[$node['fid']]) - 1; $i >= 0; $i--) {
 if ($child[$node['fid']][$i] == $id) {
 array_splice($child[$node['fid']], $i, 1);
 break;
 }
 } 
 if(count($child[$node['fid']]) == 0) {
 $child[$node['fid']] = null;
 $depth--;
 }
 }
 array_shift($stack);
 }
 $loop++;
 if($loop > 5000) return $options;
 }
 unset($child);
 unset($obj);
 return $options;
}
&#63;>
Copy after login

以上介绍的就是在不使用递归的情况下php实现无限极分类,希望对大家的学习有所帮助。

Statement of this Website
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles