Tree Algorithm-PHP Tutorial

Source: Internet
Author: User
Tree algorithm. 1, pid0), array (id2, pid0), array (id3, pid2), array (id4, pid0), array (id5, pid3), array (id6, pid1 ), array (id7, pid1), array (id8, pid6), array (id9, pid7), 1, pid => 0), array (id => 2, pid => 0), array (id => 3, pid => 2 ), array (id => 4, pid => 0), array (id => 5, pid => 3), array (id => 6, pid => 1 ), array (id => 7, pid => 1), array (id => 8, pid => 6), array (id => 9, pid => 7 ), array (id => 10, pid => 9); // sort function cmd ($ a, $ B) {if ($ a [pid] === B [pid]) return 0; return $ a [pid]> $ B [pid]? 1:-1;} // Sort. to avoid the parent node following the child node in the data, this situation often happens after data is modified multiple times // The purpose of sorting is to prevent confusion caused by this situation uasort ($ ar, cmd ); // define the target array $ d = array (); // define the index array to record the position of the node in the target array $ ind = array (); foreach ($ ar as $ v) {$ v [child] = array (); // attaches a child item to each node if ($ v [pid] = 0) {$ I = count ($ d); $ d [$ I] = $ v; $ ind [$ v [id] = & $ d [$ I];} else {$ I = count ($ ind [$ v [pid] [child]); $ ind [$ v [pid] [child] [$ I] = $ v; $ ind [$ v [id] = & $ ind [$ v [pid] [child] [$ I];} // Check the result print_r ($ d);?> Algorithm features: using the B + tree concept, a tree array can be generated in just one loop

Http://www.bkjia.com/PHPjc/531826.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/531826.htmlTechArticle1,pid=> 0), array (id => 2, pid => 0), array (id => 3, pid => 2), array (id => 4, pid => 0), array (id => 5, pid => 3), array (id => 6, pid => 1), array (id => 7, pid => 1), array (id => 8, pid => 6), array (id => 9, pid => 7),...

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.