Skip to content Skip to sidebar Skip to footer

Php Tree Change Parent Structure

I want to change structure of parent other way like Wordpress and add class if is parent. Current Structure:
  • My List

      Solution 1:

      Try this code, not ideal, but it works

      $items = [
          1 => [
              'name' => 'Menu 1',
              'children' => [2,4],
              'isChild' => false
          ],
          2 => [
              'name' => 'Menu 2',
              'children' => [3],
              'isChild' => true
          ],
          3 => [
              'name' => 'Menu 3',
              'children' => [],
              'isChild' => true
          ],
          4 => [
              'name' => 'Menu 4',
              'children' => [],
              'isChild' => true
          ],
          5 => [
              'name' => 'Menu 5',
              'children' => [],
              'isChild' => false
          ]
      ];
      
      
      
      $html = '<ul>Menu list';
      foreach($itemsas$key => $item) {
          $html .= buildMenu($item, $items);
      }
      $html .= '</ul>';
      
      echo$html;
      
      functionbuildMenu($item, $items, $listAsParent = true) {
              if($listAsParent && $item['isChild']) {
                  return;
              }
              $html = '<li>'.$item['name'];
              if(count($item['children']) != 0) {
                  $html .= '<ul class="sub-menu">';
                  foreach($item['children'] as$child) {
                      $html .= buildMenu($items[$child], $items, false);
                  }
                  $html .= '</ul>';
              }
              $html .= '</li>';
          return$html;
      }
      

      Solution 2:

      You can do that with a minor change to the function to track the menu level:

      functionmake_list($lists, $parent = 0, $level = 0) {
          $children = array_filter($lists[0], function ($v) use($parent) { return$v['parent'] == $parent; });
          if (!count($children)) return;
          echo"<ul" . ($level > 0 ? ' class="sub-menu"' : '') . ">\n";
          foreach ($childrenas$child) {
              echo"<li>{$child['name']}</li>\n";
              make_list($lists, $child['id'], ++$level);
          }
          echo"</ul>\n";
      }
      make_list($lists);
      

Post a Comment for "Php Tree Change Parent Structure"