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),...