PHP Infinite Classification Instance Program _php Tutorial

Source: Internet
Author: User
The principle of infinite classification: Just like a new folder under Windows, under the new folder can create a new folder, so infinite loop down, infinite classification is also the case, the parent class can be divided into its subclasses, subclasses can also distinguish its subclasses, so that has been infinite loop down

Example 1

The code is as follows Copy Code

$YARR = Array (
1 = = Array (' id ' = ' 1 ', ' ParentID ' =>0, ' name ' = ' first column one '),
2 = = Array (' id ' = ' 2 ', ' ParentID ' =>0, ' name ' = ' "one column II '),
3 = = Array (' id ' = ' 3 ', ' ParentID ' =>1, ' name ' = ' two ' column one '),
4 = = Array (' id ' = ' 4 ', ' ParentID ' =>1, ' name ' = ' two ' column two '),
5 = = Array (' id ' = ' 5 ', ' ParentID ' =>2, ' name ' = ' two ' column three '),
6 = = Array (' id ' = ' 6 ', ' ParentID ' =>3, ' name ' = ' three ' column one '),
7 = = Array (' id ' = ' 7 ', ' ParentID ' =>3, ' name ' = ' three ' column two '),
8 = = Array (' id ' = ' 8 ', ' ParentID ' =>2, ' name ' = ' two ' column three '),
);

/**
* Gets the child ID of the current ID
* @param array $data original arrays
* @param int $id current ID
* @param int $layer current level
*/
function Gencate ($data, $pid = 0, $level = 0)
{
if ($level = = ten) break;
$l = Str_repeat ("", $level);
$l = $l. ' └ ';
Static $arrcat = Array ();
$arrcat = Empty ($level)? Array (): $arrcat;
foreach ($data as $k = $row)
{
/**
* If the parent ID is the current incoming ID
*/
if ($row [' parentid '] = = $pid)
{
If the ID of the current traversal is not empty
$row [' name '] = $l. $row [' name '];
$row [' level '] = $level;
$arrcat [] = $row;
Var_array ($arr);
Gencate ($data, $psiff, $row [' id '], $level + 1);//Recursive call
}
}
return $arrcat;
}

$carr = Gencate ($YARR);
echo ""; foreach ($carr as $row) {echo '"; echo $row [' name ']; echo "";} echo "";

Note: Because it is an infinite number of calls, so I added a judgment, at the level of $level=10, let him jump out. No normal website will be placed over 10 levels

Directory Structure bar.

After executing to the static variable, judging the current level, if the hierarchy is 0, then this is the top-level menu, need to empty $arrcate data re-declaration


Example 2

The code is as follows Copy Code

We're building a table, "class."
CREATE TABLE ' class ' (
' id ' int (one) not NULL auto_increment COMMENT ' class ID ',
' f_id ' int (one) not NULL COMMENT ' parent id ',
' Name ' varchar collate gbk_bin not NULL COMMENT ' class name ',
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT charset=gbk collate=gbk_bin auto_increment=1;

Code

The code is as follows Copy Code
< p>< php

Header ("Content-type:text/html;charset=utf-8");

$db =new mysqli ("localhost", "root", "" "," news_php100 ");
//Instantiate a database connection. Before using this, make sure you have loaded the Mysqli class library,
or connect using mysql_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 classification of f_id=0, that is, find each large class.

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

echo $row [' name ']. " < br> "; In this way, each large class is recycled.

}

//We can also recycle the sub-categories of news.

$result = $db->query ("SELECT * from class where f_id=1");
//Find the classification of the f_id=1, that is, find the sub-class of ' news '.

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

echo $row [' name ']. "

"; This is the "news" of the sub-class loop out. Note: Only subclasses, not including grandson classes.

}

Write here we'll find a question if this classification is a level 10 classification, do we have to write
10 loops to loop each of its subclasses out? If it is more class classification, it is obviously unrealistic to write.

So what's the solution? We can write a recursive function that passes the f_id as a parameter,

The value of each f_id is constantly recycled, which means that each sub-class of the f_id value is recycled.

First, we store the values of each category in a two-dimensional array, which is useful in the recursive function below.

code as follows copy code

$result = $db->query (" SELECT * FROM Class ");

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

$arr []=array ($row [id], $row [f_id], $row [name]),//each row holds a
The Id,f_id,name information of the classification.

}

Function Fenlei ($f _id=0) {//$f _id initialized to 0, which is the start of the cycle from the largest classification.

Global $arr;//Declare $arr as a global variable to be referenced in a function.

for ($i =0; $i < count ($arr); $i + +) {//cycles through each category.

If ($arr [$i][1]== $f _id) {//$arr [$i][1] represents the f_id value of the $I+1 classification.
Start $f_id=0, that is, the f_id=0 classification output.

Echo $arr [$i][2]. " < br> "; $arr [$i][1] represents the value of the name of the $i+1 category.

Fenlei ($arr [$i][0]);//$arr [$i][1] represents the value of the ID of the $I+1 classification. Recursive
, that is, its own ID as the f_id parameter to the recycling of their own sub-class.

}

}

}

Fenlei ();//Use this function.

?>

Example 3

PHP Unlimited classification, support output tree chart

The code is as follows Copy Code

/**
* Generic tree class, which can generate any tree-type structure
*/
Class Tree
{
/**
* 2-dimensional array required to generate the tree structure
* @var Array
*/
var $arr = array ();

/**
* Create a tree structure with the necessary decoration symbols, can be converted to pictures
* @var Array
*/
var $icon = array (' │ ', ' ├ ', ' └ ');

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

The

/**
* Constructor initializes the class
* @param an array of 2-D arrays, for example:
* Array (
* 1 = array (' id ' = ' 1 ', ' ParentID ' =>0, ' name ' = > ' First level Column one '),
* 2 = = Array (' id ' = ' 2 ', ' ParentID ' =>0, ' name ' = ' A ' column two '),
* 3 = = Array (' id ' = ' 3 ', ' ParentID ' =>1, ' name ' = ' two level column one '),
* 4 = = Array (' id ' = ' 4 ', ' ParentID ' =>1, ' name ' = ' two '),
* 5 = = Array (' id ' = ' 5 ', ' ParentID ' =>2, ' name ' = ' Two-level column three '),
* 6 = = Array (' id ' = ' 6 ', ' ParentID ' =>3, ' Name ' + ' three column one '),
* 7 = = Array (' id ' = ' 7 ', ' ParentID ' =>3, ' name ' = ' three column ')
*)
*/
function Tree ($arr =array ())
{
$this->arr = $arr;
$this->ret = ";
return Is_array ($arr);
}

/**
* Get Parent Series Group
* @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 sub-series group
* @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-type structure
* -------------------------------------
* @author Midnight (Yang Yunzhou), yangyunzhou@foxmail.com
* @param $myid means to get all the children under this ID
* @param $str generate the basic code of the tree structure, for example: "

$select > $spacer $name "
* @param $sid the selected ID, such as a tree drop-down box, you need to use
* @param $adds
* @param $str _group
* @r Eturn 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 has ($list, $item) {
Return (Strpos (',, '. $list. ', ', ', '. $item. ', '));
}
}
?>

Note: No platform restrictions, only need to inform Id,parentid,name can
The above summarizes three kinds of infinite classification code have no platform limit oh, but only use in PHP, we just have to figure out the id,parentid,name of the three

System.


http://www.bkjia.com/PHPjc/444632.html www.bkjia.com true http://www.bkjia.com/PHPjc/444632.html techarticle the principle of infinite classification: Just like a new folder under Windows, under the new folder can create a new folder, so infinite loop down, infinite classification is the same, the parent class can ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.