代码之家  ›  专栏  ›  技术社区  ›  Sagar Gautam

如何在laravel刀片视图中打破foreach循环?

  •  51
  • Sagar Gautam  · 技术社区  · 7 年前

    我有一个这样的循环:

    @foreach($data as $d)
        @if(condition==true)
            {{$d}}
            // Here I want to break the loop in above condition true.
        @endif
    @endforeach
    

    如果条件满足,我想在数据显示后中断循环。

    如何在laravel刀片视图中实现?

    5 回复  |  直到 7 年前
        1
  •  110
  •   Alexey Mezenin    7 年前

    Blade docs :

    迭代:

    @foreach ($users as $user)
        @if ($user->type == 1)
            @continue
        @endif
    
        <li>{{ $user->name }}</li>
    
        @if ($user->number == 5)
            @break
        @endif
    @endforeach
    
        2
  •  6
  •   Bhaumik Pandhi    3 年前

    你可以这样打破

    @foreach($data as $d)
        @if($d === "something")
            {{$d}}
            @if(condition)
                @break
            @endif
        @endif
    @endforeach
    
        3
  •  4
  •   Hiren Gohel PRASANNA KUMAR K G    7 年前

    默认情况下,blade没有 @break @continue

    此外 $loop 变量是在循环中引入的,(几乎)就像细枝一样。

    基本示例

    @foreach($stuff as $key => $val)
         $loop->index;       // int, zero based
         $loop->index1;      // int, starts at 1
         $loop->revindex;    // int
         $loop->revindex1;   // int
         $loop->first;       // bool
         $loop->last;        // bool
         $loop->even;        // bool
         $loop->odd;         // bool
         $loop->length;      // int
    
        @foreach($other as $name => $age)
            $loop->parent->odd;
            @foreach($friends as $foo => $bar)
                $loop->parent->index;
                $loop->parent->parentLoop->index;
            @endforeach
        @endforeach 
    
        @break
    
        @continue
    
    @endforeach
    
        4
  •  0
  •   Leonel Kahameni    4 年前
    @foreach($data as $d)
        @if(condition==true)
            {{$d}}
            @break // Put this here
        @endif
    @endforeach
    
        5
  •  0
  •   Yunnosch    2 年前

    使用循环时,您也可以使用 @中断 指令:

    @foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif
    
    <li>{{ $user->name }}</li>
    
    @if ($user->number == 5)
        @break
    @endif