Php tree menu code based on recursion

Source: Internet
Author: User
This article mainly introduces the php tree menu code based on recursive implementation, and uses recursive methods to traverse nodes to construct tree menus. this is a very practical technique, for more information about php tree menu code, see the example in this article. Share it with you for your reference. The specific implementation method is as follows:

When developing an e-commerce website, the function of displaying the tree menu is implemented, and the PHP tree menu function is implemented recursively. The code is as follows:

The code is as follows:

Public function procCategory ($ sid, $ pid ){
$ Return = array ();
$ Key = 0;
Static $ arr = array (); // category level reference array
$ SQL = "select cid, pcid, name from shop_goods_catalog where sid = '{$ sid}' and pcid = '{$ pid }'";
$ Result = $ this->__ db-> query ($ SQL );

While ($ row = $ this->__ db-> fetchArray ($ result )){
$ Nbsp = '';
If ($ row ['pcid'] = 0 ){
$ Arr = array ();
}
$ Arr [] = $ row ['pcid'];
// No tree structure identifier is added for top-level classification.
If ($ row ['pcid']> 0 ){
// Add a tree structure ID based on the classification level
$ Key = array_search ($ row ['pcid'], $ arr );
For ($ I = 0; $ I <$ key; $ I ++ ){
$ Nbsp. = '';
}
// Refactored classification level reference array
If (count ($ arr)> 1 & count (array_keys ($ arr, $ row ['pcid'])> 1 ){
$ Arr = array_slice ($ arr, 0, $ key + 1 );
}
}
$ Row ['name'] = $ nbsp. $ row ['name'];
$ Row ['level'] = $ key; // category level. 0 indicates the top-level category, and 1 indicates the second-level category. it is used for style setting or other requirements.
$ Return [] = $ row;
$ R = $ this-> procCategory ($ sid, $ row ['CID']);
$ Return = array_merge ($ return, $ r );
}

Return $ return;
}


Because the recursion efficiency is relatively low, if you focus on program efficiency, do not use this method, or improve the use of this method.

I hope this article will help you with PHP programming.

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.