PHP Recursive algorithm php recursive function infinite class classification

Source: Internet
Author: User
  1. <

  2. /**
  3. * Function: Query all categories to generate tree menu
  4. * @param int $pid Parent ID start Query from top level by default
  5. */
  6. function Totree ($pid =0) {
  7. Query all top-level categories
  8. Database connections There's not much to say here.
  9. $model =m (' Category '); instantiation model
  10. Query Map criteria
  11. $map =array (
  12. ' pid ' = $pid,
  13. );
  14. Inquire
  15. $data = $model->where ($map)->select ();
  16. Defines a new array to store the generated HTML tree menu
  17. $html _array=array ();
  18. Cycle classification
  19. $html = ";
  20. $padding = 0; Indent in
  21. foreach ($data as $k = = $v) {
  22. Indent 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; Next level classification indent 20 pixels
  28. }
  29. Current categorical data HTML
  30. $data _array[]= '
  31. '. $v [' name ']. '
  32. ';

  33. Recursively start looking up sub-categories

  34. $data _array[]=totree ($v [' id ']);//recursively recursive the ID of the current classification as the parent ID
  35. }
  36. foreach Loop ends Merge categorical HTML array
  37. $html. =implode (", $data _array ());
  38. $html. = ';
  39. HTML Tree Menu Construction is complete, so simple, so easy!
  40. return $html;
  41. }

Copy Code
  • 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.