php 多种无限分类实例
创建数据库教程以及表:
CREATE DATABASE `sortclass`DEFAULT CHARSET utf8;
CREATE TABLE IF NOT EXISTS `class` (
`cid` mediumint(8) unsigned NOT NULL auto_increment,
`pid` mediumint(8) unsigned NOT NULL,
`cname` varchar(50) NOT NULL,
PRIMARY KEY (`cid`),
KEY `pid` (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
处理文件示例:
header("Content-type: text/html; charset=utf-8");
//连接数据库
$link = mysql教程_connect('localhost','root','eric') or die(mysql_error());
mysql_select_db('sortclass',$link);
//无限分类类库
class SortClass{
var $data = array();
var $child = array(-1=>array());
var $layer = array(-1=>-1);
var $parent = array();
var $link;
var $table;
function SortClass($link, $table){
$this->setNode(0, -1, '顶极节点');
$this->link = $link;
$this->table = $table;
$node = array();
$results = mysql_query('select * from '.$this->table.'',$this->link);
while($node = mysql_fetch_assoc($results)){
$this->setNode($node['cid'],$node['pid'],$node['cname']);
}
}
function setNode ($id, $parent, $value){
$parent = $parent?$parent:0;
$this->data[$id] = $value;
$this->child[$id] = array();
$this->child[$parent][] = $id;
$this->parent[$id] = $parent;
$this->layer[$id] = !isset($this->layer[$parent])? 0 : $this->layer[$parent] + 1;
}
function getList (&$tree, $root= 0){
foreach ($this->child[$root] as $key=>$id){
$tree[] = $id;
if ($this->child[$id]) $this->getList($tree, $id);
}
}
function getValue ($id){return $this->data[$id];}
function getLayer ($id, $space = false){
return $space?str_repeat($space, $this->layer[$id]):$this->layer[$id];
}
function getParent ($id){return $this->parent[$id];}
function getParents ($id){
while ($this->parent[$id] != -1){
$id = $parent[$this->layer[$id]] = $this->parent[$id];
}
ksort($parent);
reset($parent);
return $parent;
}
function getChild ($id){return $this->child[$id];}
function getChilds ($id = 0){
$child = array($id);
$this->getList($child, $id);
return $child;
}
function addNode($name,$pid){
mysql_query("insert into $this->table (`pid`,`cname`) values ('$pid','$name')",$this->link);
}
function modNode($cid, $newName){
mysql_query("update $this->table set `cname`='$newName' where `cid` = $cid",$this->link);
}
function delNode($cid){
$allChilds = $this->getChilds($cid);
$sql ='';
if(empty($allChilds)){
$sql = "delete from $this->table where `cid` = $cid";
}else{
$sql = 'delete from '.$this->table.' where `cid` in ('.implode(',',$allChilds).','.$cid.')';
}
mysql_query($sql,$this->link);
}
function moveNode($cid, $topid){
mysql_query("update $this->table set `pid`=$topid where `cid` = $cid", $this->link);
}
}
//函数
function back(){
echo '';
exit;
}
//声成select
function makeSelect($array,$formName){
global $tree;
$select = '';
}
$tree = new SortClass($link,'`class`');
$op = !empty($_POST['op']) ? $_POST['op'] : $_GET['op'];
if(!empty($op)){
if($op=='add'){
$tree->addNode($_POST['cname'],$_POST['pid']);
back();
}
if($op=='mod'){
$tree->modNode($_POST['cid'],$_POST['cname']);
back();
}
if($op=='del'){
$tree->delNode($_GET['cid']);
back();
}
if($op=='move'){
$tree->moveNode($_POST['who'],$_POST['to']);
back();
}
}
$category = $tree->getChilds();
?>
移动分类
- '.$tree->getLayer($id, '|- ').$tree->getValue($id).' Del Edit ';
foreach ($category as $id){
echo '
}
?>
简单的通过递归查询加目录path字段的无限分类
缺点:查询数据库次数太多,不方便其他操作,比如删除节点。添加节点,移动节点
2,左右值无限分类,预排序二叉树
缺点:操作繁琐,数据库冗余,且添加删除修改都要进行左右值更新
用递归无无限分页类的枋心算法
function cate_arr($arr,&$arr2=array(),$per_id=0,$lv=0){
static $i=0; //从0开始
if ((bool)$arr) {
foreach ($arr as $value) {
if ($value['per_id']==$per_id) {
$value['lv']=$lv;
$arr2[$i]=$value;
$i++;
$lv++;
cate_arr($arr,$arr2,$value['cate_id'],$lv--);
}
}
}
}
数据结构如
array(
0=>array(
'cate_id'=11,
'per_id'=0,
'cate_name'='a'
),
1=>array(
'cate_id'=12,
'per_id'=0,
'cate_name'='b'
),
2=>array(
'cate_id'=13,
'per_id'=11,
'cate_name'='a10'
),
....);
再来看一个简单的与mysqli直接连接的无限分类
header("Content-type:text/html;charset=utf-8"); $db=new mysqli("localhost","root","","news_php100") ; //实例化一个数据库连接。使用这个前一定要确保已经加载了mysqli类库,或者用mysql_connect这个方式连接。 if(mysqli_connect_errno()){ echo "链接失败:".mysqli_connect_error(); exit(); } $db->query("set names utf8"); $result=$db->query("select name from class where f_id=0"); //查找f_id=0的分类,也就是查找每一个大类。 while($row=$result->fetch_assoc()){ echo $row['name'].""; //这样就把每个大类循环出来了。 } //同样我们可以把新闻的子类循环出来。 $result=$db->query("select * from class where f_id=1"); //查找f_id=1的分类,也就是查找‘新闻’的子类。 while($row=$result->fetch_assoc()){ echo $row['name']." "; //这样就把‘新闻’的子类循环出来了。注意:只是子类,不包括孙子类。 } //写到这里,我们会发现一个问题,如果这个分类是10级分类,难道我们要写10个循环把它每个子类循环出来?如果是更多级分类呢,这样写显然是不现实的。 //那又有什么办法解决呢?我们可以写一个递归的函数,把f_id作为参数传入,不断循环每一个f_id的值,也就是说把每一个f_id值的子类循环出来。 //首先我们把各个分类的值保存在一个二维数组中,在下面的递归函数里有用。 $result=$db->query("select * from class"); while($row=$result->fetch_assoc()){ $arr[]=array($row[id],$row[f_id],$row[name]); //每一行保存一个分类的id,f_id,name的信息。 } function fenlei($f_id=0){ //$f_id初始化为0,也就是从最大分类开始循环. global $arr; //声明$arr为全局变量才可在函数里引用。 for($i=0;$i"; //$arr[$i][1]表示第$i+1个分类的name的值。 fenlei($arr[$i][0]); //$arr[$i][1]表示第$i+1个分类的id的值。进行递归,也就是把自己的id作为f_id参数把自己的子类再循环出来。 } } } fenlei(); //使用这个函数.
本分类方法的优势:
1,数据库结构简单,只有 cid parentid name 三个字段,无任何冗余字段
2,不使用递归查询,所有操作只需一条sql语句
3,所有数据在读取一次数据库后,在数组内进行分析处理,节省数据库服务器资源

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

AI Hentai Generator
Generate AI Hentai for free.

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

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

If you find event ID 55, 50, 140 or 98 in the Event Viewer of Windows 11/10, or encounter an error that the disk file system structure is damaged and cannot be used, please follow the guide below to resolve the issue. What does Event 55, File system structure on disk corrupted and unusable mean? At session 55, the file system structure on the Ntfs disk is corrupted and unusable. Please run the chkMSK utility on the volume. When NTFS is unable to write data to the transaction log, an error with event ID 55 is triggered, which will cause NTFS to fail to complete the operation unable to write the transaction data. This error usually occurs when the file system is corrupted, possibly due to the presence of bad sectors on the disk or the file system's inadequacy of the disk subsystem.

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety
