Home > Backend Development > PHP Tutorial > How does PHP achieve unlimited classification through the idea of ​​passing references (simple code), php reference_PHP tutorial

How does PHP achieve unlimited classification through the idea of ​​passing references (simple code), php reference_PHP tutorial

WBOY
Release: 2016-07-12 09:07:23
Original
783 people have browsed it

How does PHP achieve infinite classification (simple code) through the idea of ​​passing references? PHP references

unlimited classification, mainly by storing the id and classification path of the upper-level classification

In my Simpla, infinite classification is used, and PHP's passing idea is used to achieve infinite classification, which can perfectly display classification patterns like this.

id pid name
1 0   Sichuan
2 0   Chongqing
3 1 Chengdu
4 1 Mianyang
5 3 High-tech Zone

The code is as follows:

/**
  * 数组变成无限级分类--传引用思想
  * @param array $items
  * @return array
  */
 public static function get_tree($orig) {
  //解决下标不是1开始的问题
  $items = array();
  foreach ($orig as $key => $value) {
   $items[$value[‘id‘]] = $value;
  }
  //开始组装
  $tree = array();
  foreach ($items as $key => $item) {
   if ($item[‘pid‘] == 0) { //为0,则为1级分类
    $tree[] = &$items[$key];
   } else {
    if (isset($items[$item[‘pid‘]])) { //存在值则为二级分类
     $items[$item[‘pid‘]][‘child‘][] = &$items[$key]; //传引用直接赋值与改变
    } else { //至少三级分类
     //由于是传引用思想,这里将不会有值
     $tree[] = &$items[$key];
    }
   }
  }
  return $tree;
 }
Copy after login

The above content is very simple. If there are any mistakes or better methods, I hope we can communicate with each other. Thanks. !

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1060914.htmlTechArticleHow does PHP achieve infinite classification (simple code) through the idea of ​​passing references? PHP refers to infinite classification, mainly through Store the id and category path of the upper-level category to implement it in my Simpla...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template