Home > Backend Development > PHP Tutorial > PHP recursive algorithm PHP recursive function infinite classification

PHP recursive algorithm PHP recursive function infinite classification

WBOY
Release: 2016-07-25 08:54:02
Original
1017 people have browsed it
  1. <

  2. /**
  3. * Function: Query all categories to generate Tree menu
  4. * @param int $pid parent ID, query starts from the top level by default
  5. */
  6. function toTree($pid=0){
  7. //Query all top categories
  8. //Not much to say about the database connection here
  9. $model=M('Category'); Instantiate the model
  10. //Query map conditions
  11. $map=array(
  12. 'pid'=>$pid,
  13. );
  14. //Query
  15. $data=$model- >where($map)->select();
  16. //Define a new array to store the generated html tree menu
  17. $html_array=array();
  18. //Loop classification
  19. $html='';
  20. $padding=0; //Indentation
  21. foreach($data as $k=>$v){
  22. //Indentation is implemented based on the value of the path field
  23. $path=$v['path'];
  24. if( $path&&strpos($v['path'],'-')){
  25. $path_array=@explode('-',$v['path']);
  26. $count=count($path_array)-1;
  27. $padding=$count*20; //The next level classification is indented by 20 pixels
  28. }
  29. //Current classification data html
  30. $data_array[]='
  31. '.$v['name'].'
  32. ';< ;/p>
  33. //Recursively start to search for lower-level categories

  34. $data_array[]=toTree($v['id']);//Recurse using the ID of the current category as the parent ID
  35. }
  36. / /Foreach loop ends and merges classified html arrays
  37. $html.=implode('',$data_array());
  38. $html.='';
  39. //HTML tree menu construction is completed, it’s that simple, so easy!
  40. return $html;
  41. }

Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template