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.