How PHP implements the infinite Classification (code simple) _php instance by the idea of passing the reference

Source: Internet
Author: User

Infinite level classification, mainly by storing the ID of the superior category and the classification path to realize

In my simpla, I used the infinite classification, using the PHP reference idea to achieve the infinite classification method, can be perfect to show such a classification pattern.

ID PID Name
1 04 Sichuan
2 0 Chongqing
3 10% are
4 1 Mianyang
5 3 High-tech Zone

The code looks like this:

The/**
  * array becomes an infinite class--the reference thought
  * @param array $items
  * @return Array */public
 static function Get_tree ($ Orig) {
  //resolve the subscript is not the beginning of the 1 problem
  $items = Array ();
  foreach ($orig as $key => $value) {
   $items [$value [' id ']] = $value;
  }
  Start assembly
  $tree = Array ();
  foreach ($items as $key => $item) {
   if ($item [' pid '] = = 0) {//is 0, 1-level classification
    $tree [] = & $items [$key];
   } else {
    if ($items [$item [' pid ']]) {//existence value is a level two classification
     $items [$item [' pid ']][' child '] = & $items [$key]; Reference direct assignment and change
    } else {//At least level three classification
     //Because it is a reference thought, there will be no value
     $tree [] = & $items [$key]
    ;
   }
  }} return $tree;
 }

The above content is very simple, if has the mistake or the better method, hoped can communicate with each other. Thank you.!

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.