PHP Infinite Classification Instance Program

Source: Internet
Author: User
Tags foreach eval

Example 1

The code is as follows Copy Code

$YARR = Array (
1 => Array (' ID ' => ' 1 ', ' ParentID ' =>0, ' name ' => ' one-level column one '),
2 => Array (' ID ' => ' 2 ', ' ParentID ' =>0, ' name ' => ' one-level column II '),
3 => Array (' ID ' => ' 3 ', ' ParentID ' =>1, ' name ' => ' Level two column one '),
4 => Array (' ID ' => ' 4 ', ' ParentID ' =>1, ' name ' => ' Level two column two '),
5 => Array (' ID ' => ' 5 ', ' ParentID ' =>2, ' name ' => ' Level two column '),
6 => Array (' ID ' => ' 6 ', ' ParentID ' =>3, ' name ' => ' Level three column one '),
7 => Array (' ID ' => ' 7 ', ' ParentID ' =>3, ' name ' => ' Level three column two '),
8 => Array (' ID ' => ' 8 ', ' ParentID ' =>2, ' name ' => ' Level two column '),
);

/**
* Get the child ID of the current ID
* $data original Array @param array
* @param int $id current ID
* @param int $layer current level
*/
function Gencate ($data, $pid = 0, $level = 0)
{
if ($level = =) 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 current traversal ID 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 "<select>";
foreach ($carr as $row)
{
echo "<option value={$row [' id ']}> '];
echo $row [' name '];
echo "</option>";
}
echo "</select>";

Note: Because it is an infinite number of calls, I added a judgment to let him jump out of the hierarchy $level=10. No normal web site will have more than 10 floors.

Directory Structure bar.

After executing to the static variable, the current level is judged, if the level is 0, then this is the top-level menu, and you need to clear the $arrcate data.


Example 2

The code is as follows Copy Code

We build a table "class"
CREATE TABLE ' class ' (
' id ' int (one) not NULL auto_increment COMMENT ' category ID ',
' f_id ' int (one) not NULL COMMENT ' parent id ',
' Name ' varchar 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 ");
Instantiates a database connection. Make sure you've loaded the Mysqli class library before using this.
or connect it in mysql_connect this way.

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, which is to find each large class.

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

echo $row [' name ']. < br> "; This loops out every big class.

}

Again, we can recycle the news subclass.

$result = $db->query ("SELECT * from class where f_id=1");
Find the f_id=1 category, which is to find the ' news ' subclass.

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

echo $row [' name '].

"; This will be the ' news ' of the sub-class loop out. Note: Just subclasses, excluding Sun Tzu classes.

}

Writing here, we'll find a problem, if this classification is level 10, do we want to write
10 loops to loop each of its subclasses out? If it is more level classification, this writing is obviously unrealistic.

What is the solution? We can write a recursive function to pass the f_id as a parameter,

Loop through each f_id value, that is, to loop through 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 recursive function below.

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]); 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 loop starting from the largest category.

Global $arr; Declaring $arr as a global variable can be referenced in a function.

For ($i =0 $i < count ($arr), $i + +) {//loops 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 output of the f_id=0 classification.

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 category. for recursion
, which is to recycle your own subclasses as f_id parameters.

}

}

}

Fenlei (); Use this function.

?>

Example 3

PHP Infinite Classification, support output tree graph

The code is as follows Copy Code

<?php
/**
* Universal Tree class, which can generate any tree-type structure
*/
Class Tree
{
/**
* 2-D arrays required to generate a tree structure
* @var Array
*/
var $arr = array ();

/**
* Create the tree structure of the required modifiers, you can change to a picture
* @var Array
*/
var $icon = array (' │ ', ' ├ ', ' └ ');

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

/**
* Constructors, initializing classes
* @param array of array 2 dimensions, for example:
* Array (
* 1 => Array (' ID ' => ' 1 ', ' ParentID ' =>0, ' name ' => ' one-level column one '),
* 2 => Array (' ID ' => ' 2 ', ' ParentID ' =>0, ' name ' => ' one-level column II '),
* 3 => Array (' ID ' => ' 3 ', ' ParentID ' =>1, ' name ' => ' Level two column one '),
* 4 => Array (' ID ' => ' 4 ', ' ParentID ' =>1, ' name ' => ' Level two column two '),
* 5 => Array (' ID ' => ' 5 ', ' ParentID ' =>2, ' name ' => ' Level two column '),
* 6 => Array (' ID ' => ' 6 ', ' ParentID ' =>3, ' name ' => ' Level three column one '),
* 7 => Array (' ID ' => ' 7 ', ' ParentID ' =>3, ' name ' => ' Level three column two ')
*      )
*/
function tree ($arr =array ())
{
$this->arr = $arr;
$this->ret = ';
Return Is_array ($arr);
}

/**
* Get the parent progression 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;
}

   /**
 * Gets the subgroup group
 * @param int
 * @return array
 */
 func tion 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 location array
 * @param int
 * @return array
 */
 fu Nction 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;
  & nbsp;}
  }
  return $a;
 }


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

$select > $spacer $name</option> "
* @param $sid the selected ID, for example, 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. ' &nbsp; ', $str _group);
$number + +;
}
}
return $this->ret;
}
/**
* The previous method is similar, 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. <br/> ';
@extract ($a);
Eval ("$nstr =" $str ";");
$this->ret. = $nstr;
$this->get_tree_multi ($id, $str, $sid, $adds. $k. ' &nbsp; ');
$number + +;
}
}
return $this->ret;
}

function have ($list, $item) {
Return (Strpos ',,, ', ' $list. ', ', ', '. $item. '));
}
}
?>

Note: No platform limit, just need to tell 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 can be.

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.