: This article mainly introduces the implementation of PHP unlimited classification (recursion + non-recursion). If you are interested in PHP tutorials, please refer to it.
1, 'name' => 'PC', 'pid '=> 0), array ('id' => 2, 'name' => 'phone ', 'pid '=> 0), array ('id' => 3, 'name' => 'laptop', 'pid '=> 1 ), array ('id' => 4, 'name' => 'desktop ', 'pid' => 1), array ('id' => 5, 'name' => 'smartphone ', 'pid' => 2), array ('id' => 6, 'name' => 'function ', 'pid '=> 2), array ('id' => 7, 'name' => 'superscript', 'pid' => 3 ), array ('id' => 8, 'name' => 'gamely', 'pid '=> 3 ),); /* = ============= */$ tree = array (); // Step 1: use the Category id as the array key and create a children ticket Yuan foreach ($ categories as $ category) {$ tree [$ category ['id'] = $ category; $ tree [$ category ['id'] ['Children '] = array ();} // Step 2, use reference, add each category to the children array of the parent class so that a tree structure can be formed after a traversal. Foreach ($ tree as $ key => $ item) {if ($ item ['pid ']! = 0) {$ tree [$ item ['pid '] ['Children'] [] = & $ tree [$ key]; // note: the reference must be passed here. Otherwise, the result is not set to if ($ tree [$ key] ['Children '] = null) {unset ($ tree [$ key] ['Children']); // if children is empty, delete the children element (optional) }}/// step 3, delete useless non-root node data foreach ($ tree as $ key => $ category) {if ($ category ['pid']! = 0) {unset ($ tree [$ key]) ;}} print_r ($ tree ); /* = ===========*/$ tree = $ categories; function get_attr ($ a, $ pid) {$ tree = array (); // each time a new array is declared to put the child element foreach ($ a as $ v) {if ($ v ['pid '] ==$ pid) {// match the subrecord $ v ['Children'] = get_attr ($, $ v ['id']); // recursively obtain the sub-record if ($ v ['Children '] = null) {unset ($ v ['Children']); // if the child element is null, unset () is deleted, indicating that it has reached the last element of the branch (optional)} $ tree [] = $ v; // save the record to the new array} return $ tree; // return the new array} echo"
"; Print_r (get_attr ($ tree, 0 ));
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above introduces the implementation of PHP unlimited classification (recursion + non-recursion), including the content, hope to be helpful to friends interested in PHP tutorials.