Home Backend Development PHP Tutorial PHP unlimited classification example program_PHP tutorial

PHP unlimited classification example program_PHP tutorial

Jul 20, 2016 am 11:11 AM
php windows Down Classification principle Can exist Example folder New unlimited of program

The principle of infinite classification: Just like creating a new folder under Windows, you can create a new folder under the newly created folder, and this will continue in an infinite loop. The same is true for infinite classification. The parent class can be divided into subclasses, and the subclasses can be divided into subclasses. Separate its subclasses and continue in an infinite loop

Example 1

The code is as follows Copy code
 代码如下 复制代码

$yArr    = array(
     1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),
     2 => array('id'=>'2','parentid'=>0,'name'=>'一级栏目二'),
     3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),
     4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),
     5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三'),
     6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),
     7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二'),
     8 => array('id'=>'8','parentid'=>2,'name'=>'二级栏目三'),
 );
 
 /**
  * 获取当前id的子ID
  * @param array $data 原始数组
  * @param int $id 当前id
  * @param int $layer 当前层级
  */
 function genCate($data, $pid = 0, $level = 0)
 {
     if($level == 10) break;
     $l        = str_repeat(" ", $level);
     $l        = $l.'└';
     static $arrcat    = array();
     $arrcat    = empty($level) ? array() : $arrcat;
     foreach($data as $k => $row)
     {
         /**
          * 如果父ID为当前传入的id
          */
         if($row['parentid'] == $pid)
         {
             //如果当前遍历的id不为空
             $row['name']    = $l.$row['name'];
             $row['level']    = $level;
             $arrcat[]    = $row;
             //var_array($arr);
             genCate($data, $psiff, $row['id'], $level+1);//递归调用
         }
     }
     return $arrcat;
 }
 
 $carr    = genCate($yArr);
 echo "";

$yArr = array(
1 => array('id'=>'1 ','parentid'=>0,'name'=>'First-level column one'),
2 => array('id'=>'2','parentid'=> 0,'name'=>'First-level column two'),
3 => array('id'=>'3','parentid'=>1,'name'=> 'Second-level column one'),
4 => array('id'=>'4','parentid'=>1,'name'=>'Second-level column two'),
5 => array('id'=>'5','parentid'=>2,'name'=>'Second-level column three'),
6 => array('id'=>'6','parentid'=>3,'name'=>'Third-level column one'),
7 => array('id'=> '7','parentid'=>3,'name'=>'Third-level column two'),
8 => array('id'=>'8','parentid'= >2,'name'=>'Second-level column three'),
);

/**
* Get the sub-ID of the current id
* @param array $data original array
* @param int $id current id
* @param int $layer current level
>*/
function genCate($data, $pid = 0, $level = 0)
{
if($level == 10) break;
$l = str_repeat("    ", $ level);
$l = $l.'└';
static $arrcat = array();
$arrcat = empty($level) ? array() : $arrcat; foreach ($ data as $ k = & gt; $ row)
{
/**
          * If the parent ID is the currently passed in id
          * /
if ($ row ['paintid'] == $ pid )
                                                                                                       'level'] = $level;
$arrcat[] = $row;
], $level+1);//Recursive call
                                                                                                                                                           );
echo "";

Note: Because it is an infinite call, I added a judgment to let it jump out when the level $level=10. No normal website would have more than 10 levels of

directory structure.

After executing the static variable, determine the current level. If the level is 0, it means that this is the highest level menu. You need to clear the $arrcate data and re-declare it


Example 2

The code is as follows Copy code
 代码如下 复制代码

//我们建一个表"class"
CREATE TABLE `class` (
`id` int(11) NOT NULL auto_increment COMMENT '分类id',
`f_id` int(11) NOT NULL COMMENT '父id',
`name` varchar(25) collate gbk_bin NOT NULL COMMENT '分类名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;

//We create a table "class"

CREATE TABLE `class` (

`id` int(11) NOT NULL auto_increment COMMENT 'classification id',
 代码如下 复制代码

< ?php

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']."< br>"; //这样就把每个大类循环出来了。

}

//同样我们可以把新闻的子类循环出来。

$result=$db->query("select * from class where f_id=1"); 
//查找f_id=1的分类,也就是查找‘新闻’的子类。

while($row=$result->fetch_assoc()){

echo $row['name']."

"; //这样就把‘新闻’的子类循环出来了。注意:只是子类,不包括孙子类。

}

` f_id` int(11) NOT NULL COMMENT 'parent id',`name` varchar(25) collate gbk_bin NOT NULL COMMENT 'category name',PRIMARY KEY (`id`)) ENGINE= InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;
Code
The code is as follows Copy code
< ?php <🎜><🎜 >header("Content-type:text/html;charset=utf-8"); <🎜><🎜>$db=new mysqli("localhost","root","","news_php100") ; <🎜 >//Instantiate a database connection. Before using this, be sure to load the mysqli class library, <🎜> or use mysql_connect to connect. <🎜><🎜>if(mysqli_connect_errno()){<🎜><🎜>echo "Link failed:".mysqli_connect_error();<🎜><🎜>exit(); } <🎜><🎜>$db- >query("set names utf8");$result=$db->query("select name from class where f_id=0"); //Find the category of f_id=0 , that is, search for each major category. while($row=$result->fetch_assoc()){echo $row['name']."< br>"; //This way, each The major categories are cycled out. }//Similarly we can loop out the subcategories of news. $result=$db->query("select * from class where f_id=1"); //Find the category of f_id=1, that is, find the subcategory of 'news'. while($row=$result->fetch_assoc()){echo $row['name'].""; //This will The subcategory of 'News' is cycled out. Note: only subcategories, excluding grandchild categories. }

//Writing here, we will find a problem. If this classification is a 10-level classification, do we have to write
10 loops to cycle out each of its subcategories? If there are more levels of classification, it is obviously unrealistic to write like this.

//Then what’s the solution? We can write a recursive function, passing in f_id as a parameter, and

continuously looping through each f_id value, that is to say, looping out the subclasses of each f_id value.

//First we save the values ​​of each category in a two-dimensional array, which is useful in the following recursive function.

table>

?>

Example 3

php unlimited classification, supports output tree diagram

The code is as follows Copy code
 代码如下 复制代码

$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< count($arr);$i++){ //对每个分类进行循环。

if($arr[$i][1]==$f_id){ //$arr[$i][1]表示第$i+1个分类的f_id的值。
开始$f_id=0,也就是把f_id=0的分类输出来。

echo $arr[$i][2]."< br>"; //$arr[$i][1]表示第$i+1个分类的name的值。

fenlei($arr[$i][0]); //$arr[$i][1]表示第$i+1个分类的id的值。进行递归
,也就是把自己的id作为f_id参数把自己的子类再循环出来。

}

}

}

fenlei(); //使用这个函数.

$result=$db->query("select * from class");while($row=$result->fetch_assoc()){$arr[]=array($row[id],$row[f_id],$row[name]); //Each row saves the information of id, f_id, name of a category. }function fenlei($f_id=0){ //$f_id is initialized to 0, that is, the cycle starts from the largest category.global $arr; // Only by declaring $arr as a global variable can it be referenced in the function. for($i=0;$i< count($arr);$i++){ //Loop for each category. if($arr[$i][1]==$f_id){ //$arr[$i][1] represents the value of f_id of the $i+1th category. Start with $f_id=0, that is, output the classification of f_id=0. echo $arr[$i][2]."< br>"; //$arr[$i][1] represents the value of the name of the $i+1th category. fenlei($arr[$i][0]); //$arr[$i][1] represents the value of the id of the $i+1th category. Perform recursion , that is, use your own id as the f_id parameter to recycle your own subclasses. }}}fenlei(); //Use this function.
The code is as follows Copy Code

/**
* Universal tree class that can generate any tree structure
*/
class tree
{
/**
* 2-dimensional array required to generate tree structure
* @var array
* /
var $arr = array();

/**
* Modification symbols required to generate a tree structure, which can be replaced by images
* @var array
*/
var $icon = array('│','├','└');

/**
 * @access private
 */
var $ret = '';

/**
* Constructor, initialize class
* @param array 2-dimensional array, for example:
* array(
* 1 => array('id'=>'1','parentid '=>0,'name'=>'First-level column one'),
* 2 => array('id'=>'2','parentid'=>0,'name '=>'First-level column two'),
* 3 => array('id'=>'3','parentid'=>1,'name'=>'Second-level column 1'),
* 4 => array('id'=>'4','parentid'=>1,'name'=>'Second-level column two'),
* 5 => array('id'=>'5','parentid'=>2,'name'=>'Second-level column three'),
* 6 => array('id '=>'6','parentid'=>3,'name'=>'Third-level column one'),
* 7 => array('id'=>'7', 'parentid'=>3,'name'=>'Third-level column two')
* )
*/
function tree($arr=array())
{
$this->arr = $arr;
$this->ret = '';
return is_array($arr);
}

/ **
* Get the parent array
* @param int
* @return array
*/
function get_parent($myid)
{
$newarr = array();
if(!isset($this->arr[$myid])) return false;
$pid = $this->arr[$myid]['parentid'];
$pid = $this->arr[$pid]['parentid'];
if(is_array($this->arr))
{
foreach($this->arr as $id => $a)
{
if($a['parentid '] == $pid) $newarr[$id] = $a;
}
}
return $newarr;
}

/**
* Get the child array
* @param int
* @return array
*/
function get_child($myid)
{
$a = $newarr = array();
if(is_array($this->arr))
{
foreach( $this->arr as $id => $a)
{
if($a['parentid'] == $myid) $newarr[$id] = $a;
}
}
return $newarr ? $newarr : false;
}

/**
* Get the current position array
* @param int
* @return array
*/
function get_pos($myid,&$newarr)
{
$a = array();
if(!isset($this->arr[$myid])) return false;
$newarr[] = $this->arr[$ myid];
$pid = $this->arr[$myid]['parentid'];
if(isset($this->arr[$pid]))
{
$this->get_pos($pid,$newarr);
}
if(is_array($newarr))
{
krsort($newarr);
foreach($newarr as $v)
{
$a[$v['id']] = $v;
}
}
return $a;
}


/**
* -------------------------------------
* Get tree structure
* ---------------------------------------------
* @author Midnight(Yang Yunzhou), yangyunzhou@foxmail.com
* @param $myid means to get all the children under this ID
* @param $str Generate basic code of tree structure, for example: "< option value=$id

$select>$spacer$name"
* @param $sid The selected ID, such as when making a tree drop-down box.
* @param $adds
* @param $str_group
* @return unknown_type
*/
function get_tree($myid, $str, $sid = 0, $adds = '', $str_group = '')
{
$number=1;
$child = $this->get_child($myid);
if(is_array($child))
{
$total = count($ child);
foreach($child as $id=>$a)
{
$j=$k='';
if($number==$total)
{
$j .= $this->icon[2];
}
else
{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';
$selected = $id= =$sid ? 'selected' : '';
@extract($a);
$parentid == 0 && $str_group ? eval("$nstr = "$str_group";") : eval

("$nstr = "$str";");
$this->ret .= $nstr;
$this->get_tree($id, $str, $sid, $adds.$k.' ',$str_group);
$number++;
}
}
return $this->ret;
}
/**
* Similar to the previous method, but allows multiple selections
*/
function get_tree_multi($myid, $str, $sid = 0, $adds = '')
{
$number=1;
$child = $this-> ;get_child($myid);
if(is_array($child))
{
$total = count($child);
foreach($child as $id=>$a)
{
$j=$k='';
if($number==$total)
{
$j .= $this->icon[2];
}
else
{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';

$selected = $this->have($sid,$id) ? 'selected' : ' ';
//echo $sid.'=>'.$id.' : '.$selected.' .
';
@extract($a);
eval("$nstr = "$str";");
$this->ret .= $nstr;
$this->get_tree_multi($id, $str, $sid, $adds. $k.' ');
$number++;
}
}
return $this->ret;
}

function have($list, $item){
return(strpos(',,'.$list.',',','.$item.','));
}
}
?>

Note: There is no platform restriction, you only need to tell the id, parentid, name
The three unlimited classification codes summarized above have no platform restrictions, but only It can be used in php. We only need to understand the relationship between id, parentid and name.


http://www.bkjia.com/PHPjc/444632.html

truehttp: //www.bkjia.com/PHPjc/444632.htmlTechArticleThe principle of unlimited classification: just like creating a new folder under windows, you can create a new one under the new folder Folders, this loop continues indefinitely, and the same goes for infinite categories. The parent class can...
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

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

How to update the latest version of Bybit Exchange? Will there be any impact if it is not updated? How to update the latest version of Bybit Exchange? Will there be any impact if it is not updated? Feb 21, 2025 pm 10:54 PM

The way to update ByBit exchanges varies by platform and device: Mobile: Check for updates and install in the app store. Desktop Client: Check for updates in the Help menu and install automatically. Web page: You need to manually access the official website for updates. Failure to update the exchange can lead to security vulnerabilities, functional limitations, compatibility issues and reduced transaction execution efficiency.

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to install deepseek How to install deepseek Feb 19, 2025 pm 05:48 PM

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

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

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

Coinsuper exchange software channel official website entrance Coinsuper exchange software channel official website entrance Feb 21, 2025 pm 10:39 PM

The official website entrance of the Coinsuper Exchange: https://www.coinsuper.com. The client download channels are: Windows client, macOS client, and mobile (iOS/Android). Registration requires an email, mobile phone number and password, and you need to complete real-name authentication before you can trade. The platform provides a variety of digital asset transactions, including Bitcoin, Ethereum, etc., with the transaction fee rate of 0.1% for both orders and acceptors. Security safeguards include cold wallet storage, dual-factor verification, anti-money laundering and anti-terrorism financing measures, and with security public

See all articles