Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##hi
- I found this function to generate an html nested tree from a sql table.
- Here it echoes it; but I would like to return it. Possible ? How ?
- Thanks !
- function bp_classifieds_build_tree($array, $parent = 0, $level = 0,$item_fn=false) {
- // Create a function to generate a nested view of an array (looping through each array item)
- if (!$array) {
- return false;
- }
- //
- // Reset the flag each time the function is called
- //
- $has_children = false;
- //
- // Loop through each item of the list array
- //
- foreach($array as $key => $item)
- {
- //
- // For the first run, get the first item with a parent_id of 0 (= root category)
- // (or whatever id is passed to the function)
- //
- // For every subsequent run, look for items with a parent_id matching the current item's key (id)
- // (eg. get all items with a parent_id of 2)
- //
- // This will return false (stop) when it find no more matching items/children
- //
- // If this array item's parent_id value is the same as that passed to the function
- // eg. [parent_id] => 0 == $parent = 0 (true)
- // eg. [parent_id] => 20 == $parent = 0 (false)
- //
- if ($item['parent'] == $parent)
- {
- //
- // Only print the wrapper ('<ul>') if this is the first child (otherwise just print the item)
- // Will be false each time the function is called again
- //
- if ($has_children === false)
- {
- //
- // Switch the flag, start the list wrapper, increase the level count
- //
- $has_children = true;
- echo '<ul class="level-' . $level . '">';
- $level++;
- }
- //
- // Print the list item
- //
- echo '<li>';
- if ($item_fn) {
- $item_fn($item);
- } else {
- echo $item['name'];
- }
- //
- // Repeat function, using the current item's key (id) as the parent_id argument
- // Gives us a nested list of subcategories
- //
- generate_tree_list($array, $key, $level);
- //
- // Close the item
- //
- echo '</li>';
- }
- }
- //
- // If we opened the wrapper above, close it.
- //
- if ($has_children === true) echo '</ul>';
- }
- }
Add Comment
Please, Sign In to add comment