Home php教程 php手册 用PHP程序实现树状结构的两种方法

用PHP程序实现树状结构的两种方法

Jun 21, 2016 am 08:58 AM
mysql nbsp sql tree

程序

  1.递归法
  递归是指在函数中显式的调用它自身。
  利用递归法实现树状结构的特点是写入数据速度较快,显示速度较慢(在树的分支/层次较多的情况下尤其明显)。适用与写入数据量大,树的结构复杂的情况下。
  数据结构(以mysql为例)

  代码:
  CREATE TABLE `tree1` (
  `id` tinyint(3) unsigned NOT NULL auto_increment,
  `parentid` tinyint(3) unsigned NOT NULL default '0',
  `topic` varchar(50) default NULL,
  PRIMARY KEY (`id`),
  KEY `parentid` (`parentid`)
  ) TYPE=MyISAM;

  INSERT INTO `tree1` (`id`, `parentid`, `topic`) valueS 
  (1,0,'树1'),
  (2,0,'树2'),
  (3,0,'树3'),
  (4,2,'树2-1'),
  (5,4,'树2-1-1'),
  (6,2,'树2-2'),
  (7,1,'树1-1'),
  (8,1,'树1-2'),
  (9,1,'树1-3'),
  (10,8,'树1-2-1'),
  (11,7,'树1-1-1'),
  (12,11,'树1-1-1-1');

  
  字段说明
  id,记录的id号
  parentid,记录的父记录id(为0则为根记录)
  topic,记录的显示标题

  显示程序

  顺序树:

  PHP:

  
  /* 数据库连接 */
  mysql_connect();
  mysql_select_db('tree');

  /* 树状显示的递归函数 */
  function tree($parentid = 0) {
  /*执行sql查询,获取记录的标题和id*/
  $sql = "select topic,id from tree1 where 

parentid = $parentid order by id asc";
  $rs = mysql_query($sql);
  /* 缩进*/
  echo("

    ");
      while($ra = mysql_fetch_row($rs)) {
      /* 显示记录标题 */
      echo('
  • '.$ra[0].'
  • ');
      /* 递归调用 */
      tree($ra[1]);
      }
      echo("
");
  }
  tree();
  ?>

  逆序树:

  PHP:

  
  /* 数据库连接 */
  mysql_connect();
  mysql_select_db('tree');

  /* 树状显示的递归函数 */
  function tree($parentid = 0) {
  /*执行sql查询,获取记录的标题和id*/
  $sql = "select topic,id from tree1 where parentid

 = $parentid order by id desc";
  $rs = mysql_query($sql);
  /* 缩进*/
  echo("

    ");
      while($ra = mysql_fetch_row($rs)) {
      /* 显示记录标题 */
      echo('
  • '.$ra[0].'
  • ');
      /* 递归调用 */
      tree($ra[1]);
      }
      echo("
");
  }
  tree();
  ?>

  插入数据程序

  PHP:

  
  /* 数据库连接 */
  mysql_connect();
  mysql_select_db('tree');
  $sql = "insert into tree (topic,parentid) values('树3-1',3);";
  mysql_query($sql);
  ?>

  2.排序字段法
  此方法是通过在数据结构中增加一个标志记录在整个树中的顺序位置的字段来实现的。特点是显示速度和效率高。但在单个树的结构复杂的情况下,数据写入效率有所不足。而且顺序排列时候,插入,删除记录的算法过于复杂,故通常用逆序排列。

  数据结构(以mysql为例)

  代码:
  CREATE TABLE `tree2` (
  `id` tinyint(3) unsigned NOT NULL auto_increment,
  `parentid` tinyint(3) unsigned NOT NULL default '0',
  `rootid` tinyint(3) unsigned NOT NULL default '0',
  `layer` tinyint(3) unsigned NOT NULL default '0',
  `orders` tinyint(3) unsigned NOT NULL default '0',
  `topic` varchar(50) default NULL,
  PRIMARY KEY (`id`),
  KEY `parentid` (`parentid`),
  KEY `rootid` (`rootid`)
  ) TYPE=MyISAM

  INSERT INTO `tree2` (`id`, `parentid`, `rootid`,

 `layer`, `orders`, `topic`) valueS 
  (1,0,1,0,0,'树1'),
  (2,0,2,0,0,'树2'),
  (3,0,3,0,0,'树3'),
  (4,2,2,1,2,'树2-1'),
  (5,4,2,2,3,'树2-1-1'),
  (6,2,2,1,1,'树2-2'),
  (7,1,1,1,4,'树1-1'),
  (8,1,1,1,2,'树1-2'),
  (9,1,1,1,1,'树1-3'),
  (10,8,1,2,3,'树1-2-1'),
  (11,7,1,2,5,'树1-1-1'),
  (12,11,1,3,6,'树1-1-1-1');

  
  显示程序

  PHP:

  
  /* 数据库连接 */
  mysql_connect();
  mysql_select_db('tree');

  /* 选出所有根记录id */
  $sql = "select id from tree2 where parentid = 0 order by id desc";
  $rs = mysql_query($sql);
  echo("

    ");
      $lay = 0;
      while($ra = mysql_fetch_row($rs)) {
      echo("
      ");
        /* 选出此树所有记录,并按orders字段排序 */
        $sql = "select topic,layer from tree2 where

       rootid = $ra[0] order by orders";
        $rs1 = mysql_query($sql);
        while($ra1 = mysql_fetch_row($rs1)) {
        /* 缩进显示 */
        if($ra1[1]>$lay) {
        echo(str_repeat("

        ",$ra1[1]-$lay));
          }elseif($ra1[1]  echo(str_repeat("
      ",$lay-$ra1[1]));
        }
        /* 记录显示 */
        //echo("$ra1[1]>$lay");
        echo("
    • $ra1[0]
    • ");
        $lay = $ra1[1];
        }
        echo("
    ");
      }
      echo("
");
  ?>

  插入数据程序

  PHP:

  
  /* 数据库连接 */
  mysql_connect();
  mysql_select_db('tree');

  /* 插入根记录 */
  $sql = "insert into tree2 (topic) values ('树5')";
  mysql_query($sql);
  $sql = "update tree2 set rootid = id where id = ".mysql_insert_id();
  mysql_query($sql);

  /* 插入子记录 */
  $parentid = 5;//父记录id
  /* 取出 根记录id,父记录缩进层次,父记录顺序位置 */
  $sql = "select rootid,layer,orders from tree2 where id = $parentid";
  list($rootid,$layer,$orders) = mysql_fetch_row(mysql_query($sql));
  /* 更新插入位置后记录的orders值 */
  $sql = "update tree2 set orders = orders + 1 where orders > $orders";
  mysql_query($sql);
  /* 插入记录 */
  $sql = "insert into tree2 (rootid,parentid,orders,

layer,topic) values ($rootid,$parentid,".($orders+1).",".($layer+1).",'树2-1-1-2')";
  mysql_query($sql);?>
  



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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to build a SQL database How to build a SQL database Apr 09, 2025 pm 04:24 PM

Building an SQL database involves 10 steps: selecting DBMS; installing DBMS; creating a database; creating a table; inserting data; retrieving data; updating data; deleting data; managing users; backing up the database.

See all articles