Infinitely classified search-descendant tree, family tree

Source: Internet
Author: User
Unlimited classification search
$ Area = array (
Array ('id' => 1, 'name' => 'Beijing', 'parent' => 0 ),
Array ('id' => 2, 'name' => 'changping ', 'parent' => 1 ),
Array ('id' => 3, 'name' => 'haidian ', 'parent' => 2 ),
Array ('id' => 4, 'name' => 'Tianjin city ', 'parent' => 0 ),
Array ('id' => 5, 'name' => 'municipal authority ', 'parent' => 4 ),
Array ('id' => 6, 'name' => 'peaceful region', 'parent' => 5 ),
Array ('id' => 7, 'name' => 'hebei province ', 'parent' => 0 ),
Array ('id' => 8, 'name' => 'shijiazhuang city ', 'parent' => 7 ),
Array ('id' => 9, 'name' => 'Chang 'an District ', 'parent' => 8)
);

1: Find the subtree: Find the subnode under this node

/*** Find the subtree, subnode */function findson ($ arr, $ id = 0) {$ sons = array (); foreach ($ arr as $ value) {if ($ value ['parent'] ==$ id) {$ sons = $ value ;}} return $ sons ;} print_r (findson ($ area, 0 ));

2: Search for the child tree: find all the child nodes under the node and the child nodes under the child node, infinite search, until there is no child node, this uses recursive call to find.

/*** Find descendant tree */function subtree ($ arr, $ id, $ lev= 1) {$ subs = array (); foreach ($ arr as $ value) {if ($ value ['parent'] ==$ id) {$ value ['lev'] = $ lev; $ subs [] = $ value; $ subs = array_merge ($ subs, subtree ($ arr, $ value [id], $ annually + 1) ;}} return $ subs ;}

3: Search for the genealogy tree: find all the parent nodes of the node and continue to search for them through the parent node. The recursive call here is slightly different from the above, here, the array processing method is through the static keyword.

/*** Family tree */function familytree ($ arr, $ id) {static $ tree = array (); foreach ($ arr as $ value) {if ($ value ['id'] ==$ id) {$ tree [] = $ value; if ($ value ['parent']> 0) {familytree ($ arr, $ value ['parent']) ;}} return $ tree ;}

 

Infinitely classified search-descendant tree, family tree

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.