How does PHP implement unlimited classification through the idea of transferring references (simple code)

Source: Internet
Author: User
This article describes how to use the reference transfer method in php to implement unlimited classification. the code is extremely simple and can be used by anyone who needs it, it is mainly implemented by storing the id and path of the upper-level classification.

In my Simpla, I used unlimited classification. I used the reference transfer idea of PHP to implement an infinite classification method, which perfectly demonstrated a classification mode similar to this.

Id pid name
1 0 Sichuan
2 0 Chongqing
3 1 Chengdu
4 1 Mianyang
5 3 high-tech zones

The code is as follows:

/*** Convert an array into an infinite classification-transmit the reference idea * @ param array $ items * @ return array */public static function get_tree ($ orig) {// solve the problem that subscript is not from 1 $ items = array (); foreach ($ orig as $ key => $ value) {$ items [$ value ['id'] = $ value;} // Start Assembly $ tree = array (); foreach ($ items as $ key => $ item) {if ($ item ['pid '] = 0) {// if the value is 0, $ tree [] = & $ items [$ key];} else {if (isset ($ items [$ item ['pid ']) {// if a value exists, it is a second-level classification. $ items [$ item ['pid '] ['child'] [] = & $ items [$ key]; // direct value assignment and change for transferring references} else {// at least three levels of classification // because it is a reference transfer idea, $ tree [] = & $ items [$ key] ;}} return $ tree ;}

The above content is very simple. if there is an error or a better method, we hope we 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.