0

I am currently echoing an array coming from a query and I need to present them in nested unordered lists. I am trying to find a way to do this procedure infinitely because I am currently manually echoing each nested ul's (if they have one) only up to the depth that I manually code. Please help me if there is a way to automatically echo the ul's up to depth "n".

This is my current logic only echoing up to depth 5:

<ul class="parent_tree"><?php
  foreach($category_tree as $category_level_1)
  {
    echo '<li><a href="#">' . $category_level_1['name'] . '</a>';

    if(array_key_exists('children', $category_level_1))
    {
      echo '<ul>';

      foreach($category_level_1['children'] as $category_level_2)
      {
        echo '<li><a href="#">' . $category_level_2['name'] . '</a>';

        if(array_key_exists('children', $category_level_2))
        {
          echo '<ul>';

          foreach($category_level_2['children'] as $category_level_3)
          {
            echo '<li><a href="#">' . $category_level_3['name'] . '</a>';

            if(array_key_exists('children', $category_level_3))
            {
              echo '<ul>';

              foreach($category_level_3['children'] as $category_level_4)
              {
                echo '<li><a href="#">' . $category_level_4['name'] . '</a>';

                if(array_key_exists('children', $category_level_4))
                {
                  echo '<ul>';

                  foreach($category_level_4['children'] as $category_level_5)
                  {
                    echo '<li><a href="#">' . $category_level_5['name'] . '</a>';

                    //level 6 goes here

                    echo '</li>';
                  }

                  echo '</ul>';
                }

                echo '</li>';
              }

              echo '</ul>';
            }

            echo '</li>';
          }

          echo '</ul>';
        }

        echo '</li>';
      }

      echo '</ul>';
    }

    echo '</li>';
  }
?>
</ul>
4

1 に答える 1

1

テストしていませんが、これには再帰を使用する必要があります。基本的に、同じ関数を異なるパラメーターで呼び出し続けます。すべてをループし、子配列がなくなると終了します。

function recursive_list($category) {
    echo '<ul>';
    foreach($category as $item){
        echo '<li><a href="#">' . $item['name'] . '</a>';
        if(array_key_exists('children', $item)) {
            recursive_list($item);
        }
    }
}
于 2013-02-21T04:15:01.337 に答える