无限分类与树型论坛的实现方法_PHP
无限分类与树型论坛的实现方法
――浮点型字段排序法
Joe Teng 2005.6.12
在此我不想讨论其他实现方法的利与弊。
既然是使用字段排序,那么我们便设一个名为order的字段。问题是,在这里是使用整数还是使用浮点数类型呢?考虑到会有在两个连续order值中间插入新值的可能,自然是需要使用浮点类型了。
建一个menus表,我们还需要以下字段:
id : 类别编号
mainid : 主分类编号,但不作具体分类使用。如果在树型论坛里,它代表的是主题id
parentid : 父类编号
level : 类别级别,作用其实是方便显示的时候作其他处理
info : 类别名称等。
由此可以得到menus的表结构:
CREATE TABLE `menus` (
`id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
`mainid` INT( 10 ) UNSIGNED NOT NULL ,
`parentid` INT( 10 ) UNSIGNED NOT NULL ,
`order` FLOAT UNSIGNED NOT NULL ,
`level` SMALLINT( 5 ) UNSIGNED NOT NULL ,
`info` VARCHAR( 128 ) NOT NULL ,
INDEX ( `mainid` , `parentid` , `order` , `level` ) ,
UNIQUE (
`id`
)
) TYPE = MYISAM ;
很容易可以看出,输入的时候是如此简单便实现树结构了:
SELECT * FROM `menus` ORDER BY `mainid` ASC, `order` ASC ;
前提是添加类别的时候,order能正确排序。
添加根分类:
很简单,取得上一个主类的mainid, 如A_mainid,则新根分类的mainid则为A_mainid + 1。parentid 为 0 , order 为0, level也为0, info则自行设定。
添加子分类:
核心思想是,取得新增子分类的前一个分类的order以及它后一个分类的order。
取得前一个分类的order是这里的难点,因为涉及到同级与非同级的情况。非同级的情况很简单,新增别类的前一个order其实就是它的父类的order。如果有同级分类,情况就很复杂了,因为它前面的同级分类有可能会拥有子分类,子分类下又可能还会有子分类,如此下来,要取得前一个order就很难了。
解决的办法有两个:
1.取得新增类同级的前一个类别,如类别A的ID,使用递归的方法,直到取得A类别下最后最小分类的order,那便是要新增分类的前一个order了。这种方法的缺点是,如果A类别下有很多子分类,那么递归需要一定的时间。这种方法适用于普通的分类处理,不适用于树型论坛。不过总体来说,因为是添加类别的时候才使用递归,输出类别的时候跟前面一样,效率还是很高的。
2.作一个记录,记录着与A有关联的最后order。于是我们就需要增加一个表,建利关系树。这种关系树做起来很简单。表结构如下:
CREATE TABLE `menu_tree` (
`mainid` int(10) unsigned NOT NULL default '0',
`tree` text NOT NULL,
`order` float unsigned NOT NULL default '0',
KEY `mainid` (`mainid`,`order`),
FULLTEXT KEY `tree` (`tree`)
) TYPE=MyISAM;
(构建方式请看我后面给出的源码)
取得前一个order之后,要取得后一个order就很简单了。取同mainid下大于前一个order的最小order便是了。如果存在后一个order,那么新增order就取前一个order与后一个order的平均值。如果不存在后一个order,那说明新增类别是main下的最小order,取大于前一个order的最小整数就行了。
主要实现方法便如上面说的。
处理方法
/*
* ID: class FreeRoad
* Author: Joe Teng
* Notice: Infinite category maker.
*/
(
"host" => 'localhost', "user" => 'root', "password" => '123456', "dbname" => 'test'
);
$resDbc = mysql_connect ( $arrDatabase["host"], $arrDatabase["user"], $arrDatabase["password"] );
mysql_select_db( $arrDatabase['dbname'] );
if ( ! class_exists ( "FreeRoad" ))
{
class FreeRoad
{
var $resDbc ;
var $strDatabase ;
var $strMenuTable ;
var $strMenuTreeTable ;
var $strFiled_id = 'id' ;
var $strFiled_mainid = 'mainid' ;
var $strFiled_parentid = 'parentid' ;
var $strFiled_order = 'order' ;
var $strFiled_level = 'level' ;
function FreeRoad ( $resDbc , $strDatabase , $strMenuTable , $strMenuTreeTable , $arrSetFileds = array() )
{
$this->resDbc = $resDbc ;
$this->strDatabase = $strDatabase;
$this->strMenuTable = $strMenuTable ;
$this->strMenuTreeTable = $strMenuTreeTable ;
if ( sizeof ( $arrSetFileds ) > 0 )
{
$this->strFiled_id = $arrSetFileds['id'] ;
$this->strFiled_mainid = $arrSetFileds['mainid'] ;
$this->strFiled_parentid = $arrSetFileds['parentid'] ;
$this->strFiled_order = $arrSetFileds['order'] ;
$this->strFiled_level = $arrSetFileds['level'] ;
}
}
function get_new_mainid ()
{
mysql_select_db ( $this->strDatabase , $this->resDbc ) ;
$strQuery = " SELECT `$this->strFiled_mainid`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_parentid` = 0
ORDER BY `$this->strFiled_id` DESC LIMIT 0 , 1 " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_array ( $resResult ) )
{
$intLastedMainId = $arrRow[0] ;
}
$intLastedMainId = intval ( $intLastedMainId );
mysql_free_result ( $resResult ) ;
return $intLastedMainId + 1 ;
}
function get_level_lastest_id ( $intParentId )
{
mysql_select_db ( $this->strDatabase , $this->resDbc ) ;
$strQuery = " SELECT `$this->strFiled_id`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_parentid` = $intParentId
ORDER BY `$this->strFiled_id` DESC LIMIT 0 , 1 " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$intLevelLastestId = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
return $intLevelLastestId ;
}
function get_level_lastest_order ( $intParentId )
{
mysql_select_db ( $this->strDatabase , $this->resDbc ) ;
$strQuery = " SELECT `$this->strFiled_order`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_id` = $intParentId " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$floSelectItemOrder = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
$strQuery = " SELECT `$this->strFiled_order`
FROM `$this->strMenuTreeTable`
WHERE BINARY ( `tree`) LIKE '%|$intParentId|%'
ORDER BY `$this->strFiled_order` DESC LIMIT 0 , 1 " ;
//echo $strQuery ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$floSelectItemLastestOrder = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
if ( ! $floSelectItemLastestOrder ) $floSelectItemLastestOrder = $floSelectItemOrder ;
return $floSelectItemLastestOrder ;
}
function get_elements ( $intParentId = 0 )
{
mysql_select_db ( $this->strDatabase , $this->resDbc ) ;
if ( $intParentId == 0 )
{
$intMainId = $this->get_new_mainid ( );
return array ( "mainid" => $intMainId , "order" => 0 , "level" => 0 ) ;
}
$strQuery = " SELECT `$this->strFiled_mainid` , `$this->strFiled_order` , `$this->strFiled_level`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_id` = $intParentId " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$intMainId = $arrRow[0] ;
$floOrder = $arrRow[1] ;
$intLevel = $arrRow[2] ;
}
mysql_free_result ( $resResult ) ;
if ( ! $intMainId ) return false ;
$intLevelLastestId = $this->get_level_lastest_id ( $intParentId ) ;
// get pre order
if ( $intLevelLastestId )
{
$floPreOrder = $this->get_level_lastest_order ( $intLevelLastestId );
// echo $floPreOrder ;exit;
}
else
{
$floPreOrder = $floOrder ;
}
// get next order
$strQuery = " SELECT `$this->strFiled_order`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_mainid` = $intMainId AND `$this->strFiled_order` > $floPreOrder
ORDER BY `$this->strFiled_order` ASC LIMIT 0 , 1 " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$floNextOrder = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
if ( ! $floNextOrder )
{
$floNewOrder = floor ( $floPreOrder + 1 ) ;
}
else
{
$floNewOrder = number_format ( ( $floPreOrder + $floNextOrder ) / 2 , 14 ) ;
}
$intNewLevel = $intLevel + 1 ;
return array ( "mainid" => $intMainId , "order" => $floNewOrder , "level" => $intNewLevel ) ;
}
function update_tree ( $intMainId , $intParentId , $floOrder )
{
if ( !$intParentId ) return false ;
mysql_select_db ( $this->strDatabase , $this->resDbc ) ;
$strQuery = " SELECT `tree`
FROM `$this->strMenuTreeTable`
WHERE `mainid` = $intMainId AND BINARY ( `tree`) LIKE '%|$intParentId|'
ORDER BY `order` DESC LIMIT 0 , 1 " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$strTree = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
if ( ! $strTree )
{
$strQuery = " SELECT `$this->strFiled_parentid`
FROM `$this->strMenuTable`
WHERE `$this->strFiled_id` = $intParentId " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$intPreParentId = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
if ( ! $intPreParentId )
{
$strPreTree = '';
}
else
{
$strQuery = " SELECT `tree`
FROM `$this->strMenuTreeTable`
WHERE `mainid` = $intMainId AND BINARY ( `tree`) LIKE '%|$intPreParentId|'
ORDER BY `order` DESC LIMIT 0 , 1 " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
while ( $arrRow = mysql_fetch_row ( $resResult ) )
{
$strPreTree = $arrRow[0] ;
}
mysql_free_result ( $resResult ) ;
}
$strNewTree = $strPreTree . '|'. $intParentId . '|' ;
$strQuery = " INSERT INTO `$this->strMenuTreeTable`
VALUES ( $intMainId, '$strNewTree', $floOrder ) " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
@mysql_free_result ( $resResult ) ;
return true ;
}
else
{
$strQuery = " UPDATE `$this->strMenuTreeTable`
SET `order` = $floOrder
WHERE `mainid` = $intMainId AND `tree` = '$strTree' " ;
$resResult = mysql_query ( &$strQuery , $this->resDbc ) ;
@mysql_free_result ( $resResult ) ;
return true ;
}
}
}
}
/*
$pFreeRoad = new FreeRoad ( $resDbc , $arrDatabase["dbname"] , 'menus' , 'menu_tree' ) ;
$info = 'change here';
$intParentId = change here ;
$arrItems = $pFreeRoad->get_elements( $intParentId ) ;
$intMainId = $arrItems['mainid'] ;
$floOrder = $arrItems['order'] ;
$intLevel = $arrItems['level'] ;
$strQuery = " INSERT INTO `menus` VALUES ( '' , $intMainId , $intParentId , $floOrder , $intLevel, '$info' ) " ;
$resResult = mysql_query ( &$strQuery , $resDbc ) ;
$pFreeRoad->update_tree ( $intMainId , $intParentId , $floOrder ) ;
@mysql_close( $resDbc ) ;
*/
?>
include "freeroad.class.php";
$strQuery = " SELECT * FROM `menus` ORDER BY `mainid` ASC , `order` ASC ";
$resResult = mysql_query ( &$strQuery , $resDbc ) ;
while ( $arrRows = mysql_fetch_array ( $resResult ))
{
$intLevel = $arrRows["level"] ;
$strSpace = '' ;
for ( $i = 0 ; $i $intLevel ; $i++ )
{
$strSpace .= " ";
}
if ( $i>1 )
{
$strSpace .= '--';
}
echo $strSpace . $arrRows["id"] . $arrRows["info"] ."
";
}
if ( $_GET["action"] == 'add' )
{
$pFreeRoad = new FreeRoad ( $resDbc , $arrDatabase["dbname"] , 'menus' , 'menu_tree' ) ;
$info = 'F1';
$intParentId = 1 ;
$arrItems = $pFreeRoad->get_elements( $intParentId ) ;
$intMainId = $arrItems['mainid'] ;
$floOrder = $arrItems['order'] ;
$intLevel = $arrItems['level'] ;
$strQuery = " INSERT INTO `menus` VALUES ( '' , $intMainId , $intParentId , $floOrder , $intLevel, '$info' ) " ;
$resResult = mysql_query ( &$strQuery , $resDbc ) ;
$pFreeRoad->update_tree ( $intMainId , $intParentId , $floOrder ) ;
@mysql_close( $resDbc ) ;
}
?>
容易可以看出,输出的时候是如此简单便实现树结构了:
SELECT * FROM `menus` ORDER BY `mainid` ASC, `order` ASC ;
前文输出写成输入了~~~ 晕倒。。
输出的时候,根据level来做树结构。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence
