php Tree Menu Code Based on Recursive Implementation

  • 2021-08-05 09:08:16
  • OfStack

In this paper, an example is given to describe the php tree menu code based on recursion. Share it for your reference. The specific implementation method is as follows:

The development of e-commerce website, do this display tree menu function, with the recursive realization of PHP tree menu function. The specific code is as follows:

public function procCategory($sid,$pid){
$return = array();
$key = 0;
static $arr = array(); // Classification 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'];
// The top-level classification does not add a tree structure identity.
if($row['pcid']>0){
// Add tree structure identification according to classification level
$key = array_search($row['pcid'],$arr);
for($i=0;$i<$key;$i++){
$nbsp .= '&nbsp;&nbsp;';
}
// Refactoring the 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; // Classification level, 0 For the top-level classification, 1 For 2 Level classification, used for style setting or other requirements
$return[] = $row;
$r = $this->procCategory($sid,$row['cid']);
$return = array_merge($return,$r);
}
 
return $return;
}

Because the efficiency of recursion is relatively low, if we pay attention to the efficiency of the program, do not use this method, or improve the use of this method.

I hope this article is helpful to everyone's PHP programming.


Related articles: