【问题标题】:PHP - "n" number of children in a listPHP - 列表中的“n”个孩子
【发布时间】:2015-10-20 06:27:03
【问题描述】:

此问题与:Group by in Laravel 5

基本上,我所拥有的是一系列“组”,每个组可以拥有任意数量的子组。所以它可能看起来像这样:

  • 第 1 组
    • 第 1 组儿童
      • 第 1 组的孩子
        • 第 1 组 1 的孩子
  • 第 2 组

目前,我只能使用以下方式显示该组及其孩子:

    <ul>
@foreach($contents as $content)
  <li>{{$content->title}}</li>
  @if($content->children->count() > 0)
    <ul>
      @foreach($content->children as $childContent)
        <li>{{$childContent->title}}</li>
      @endforeach
   </ul>
  @endif
@endforeach
</ul> 

如果我想添加更多的子层,我必须用另一个if 语句和foreach 语句来编写代码。显然,当一个组有 n^3,... 个孩子时,这是不切实际的。

是否有动态的while-loop 方法来解决这个问题?任何帮助将不胜感激!!

【问题讨论】:

    标签: php mysql laravel laravel-5 blade


    【解决方案1】:

    您需要的是一个递归部分 - 只要有更多的组级别要显示,它就会自行加载。

    // list_group.blade.php
    <li>
      {{ $content->title }}
      @if($content->children->count() > 0)
        <ul>
          @foreach($content->children as $childContent)
            @include('list_group', array('content' => $childContent))
          @endforeach
        </ul>
      @endif
    </li>
    
    //in your template 
    <ul>
      @foreach($contents as $content)
        @include('list_group', array('content' => $content))
      @endforeach
    </ul>
    

    【讨论】:

    • 感谢您的回复。即使我将它放在同一个文件夹中,我也会收到“未找到视图”?
    • 你放的文件夹路径是什么?
    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    相关资源
    最近更新 更多