Guest User

Untitled

a guest
Jun 22nd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. ##hi
  2. I found this function to generate an html nested tree from a sql table.
  3. Here it echoes it; but I would like to return it. Possible ? How ?
  4. Thanks !
  5.  
  6. function bp_classifieds_build_tree($array, $parent = 0, $level = 0,$item_fn=false) {
  7. // Create a function to generate a nested view of an array (looping through each array item)
  8.  
  9. if (!$array) {
  10. return false;
  11. }
  12.  
  13. //
  14. // Reset the flag each time the function is called
  15. //
  16. $has_children = false;
  17.  
  18. //
  19. // Loop through each item of the list array
  20. //
  21. foreach($array as $key => $item)
  22. {
  23. //
  24. // For the first run, get the first item with a parent_id of 0 (= root category)
  25. // (or whatever id is passed to the function)
  26. //
  27. // For every subsequent run, look for items with a parent_id matching the current item's key (id)
  28. // (eg. get all items with a parent_id of 2)
  29. //
  30. // This will return false (stop) when it find no more matching items/children
  31. //
  32. // If this array item's parent_id value is the same as that passed to the function
  33. // eg. [parent_id] => 0 == $parent = 0 (true)
  34. // eg. [parent_id] => 20 == $parent = 0 (false)
  35. //
  36. if ($item['parent'] == $parent)
  37. {
  38.  
  39. //
  40. // Only print the wrapper ('<ul>') if this is the first child (otherwise just print the item)
  41. // Will be false each time the function is called again
  42. //
  43. if ($has_children === false)
  44. {
  45. //
  46. // Switch the flag, start the list wrapper, increase the level count
  47. //
  48. $has_children = true;
  49.  
  50. echo '<ul class="level-' . $level . '">';
  51.  
  52. $level++;
  53. }
  54.  
  55. //
  56. // Print the list item
  57. //
  58. echo '<li>';
  59.  
  60. if ($item_fn) {
  61. $item_fn($item);
  62. } else {
  63. echo $item['name'];
  64. }
  65.  
  66. //
  67. // Repeat function, using the current item's key (id) as the parent_id argument
  68. // Gives us a nested list of subcategories
  69. //
  70. generate_tree_list($array, $key, $level);
  71.  
  72. //
  73. // Close the item
  74. //
  75. echo '</li>';
  76.  
  77.  
  78. }
  79.  
  80. }
  81.  
  82. //
  83. // If we opened the wrapper above, close it.
  84. //
  85. if ($has_children === true) echo '</ul>';
  86. }
  87. }
Add Comment
Please, Sign In to add comment