Recursive UL Output with name-based array keys


/ Published in: PHP
Save to your folder(s)

Can probably be done easier/better, but it accomplishes what I needed it to do. Figured I'd share.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function recursion($multi_dimensional_array)
  4. {
  5. $m = $multi_dimensional_array;
  6.  
  7. $keys = array();
  8. foreach($m as $key=>$value)
  9. {
  10. $keys[] = $key;
  11. }
  12.  
  13. $i = 0;
  14. while($i < count($multi_dimensional_array))
  15. {
  16. echo '<li><a href="#">'.$keys[$i].'</a>';
  17. if(is_array($multi_dimensional_array[$keys[$i]]))
  18. {
  19. echo '<ul>';
  20. recursion($multi_dimensional_array[$keys[$i]]);
  21. echo '</ul>';
  22. }
  23. echo '</li>';
  24. $i++;
  25. }
  26. }
  27.  
  28. ?>
  29.  
  30. Usage Example:
  31.  
  32. <ul>
  33. <? recursion($array); ?>
  34. </ul>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.