AVONnadozie

Display Array as Tree

Mar 16th, 2018
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.74 KB | None | 0 0
  1. <?php
  2. $listItems = [
  3.     'Programming' => [
  4.         'PHP' => ['Laravel', 'CodeIgniter'],
  5.         'Python',
  6.         'Java'
  7.     ],
  8.     'Movies' => [
  9.         'The Matrix',
  10.         'Lord of the Rings'
  11.     ],
  12.     'Music',
  13.     'Sports',
  14.     'Livestyle'
  15. ];
  16.  
  17. //printTree
  18. function generateHtmlMenu(array $array)
  19. {
  20.     if (empty($array)) {
  21.         return '';
  22.     }
  23.  
  24.     $list = '<ul>';
  25.     foreach ($array as $key => $value) {
  26.         $list .= '<li>';
  27.         if (is_array($value)) {
  28.             $list .= $key;
  29.             $list .= generateHtmlMenu($value);
  30.         } else {
  31.             $list .= $value;
  32.         }
  33.         $list .= '</li>';
  34.     }
  35.     $list .= '</ul>';
  36.     return $list;
  37. }
  38.  
  39. echo generateHtmlMenu($listItems);
  40. ?>
Advertisement
Add Comment
Please, Sign In to add comment