php Laravel Blade:每次将变量增加 1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30919278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Blade: Increment variable by 1 each time?
提问by I'll-Be-Back
Using Laravel blade template, is there a way to include a variable and increase each time in the foreach or what is better approach?
使用 Laravel 刀片模板,有没有办法在 foreach 中包含一个变量并每次增加,或者有什么更好的方法?
For example:
例如:
@foreach($categories as $category)
<li><a href="#tab_c1" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach
In the foreach
block, the value from #tab_c1 will need to be increase. eg: #tab_c1, #tab_c2, #tab_c3
在foreach
块中,#tab_c1 中的值需要增加。例如:#tab_c1, #tab_c2, #tab_c3
回答by Limon Monte
Add iterator to @foreach
:
将迭代器添加到@foreach
:
@foreach($categories as $key => $category)
<li @if ($key === 0) class="active" @endif>
<a href="#tab_c{{$key+1}}" role="tab" data-toggle="tab">
{{$category->name}}
</a>
</li>
@endforeach
{{$key+1}}
in my example because in PHP iterator starts at 0.
{{$key+1}}
在我的例子中,因为在 PHP 中迭代器从 0 开始。
回答by kosta
In Laravel 5.3 you can use The Loop Variable, $loop->iteration for concrete situation. https://laravel.com/docs/5.3/blade#the-loop-variable
在 Laravel 5.3 中,您可以使用循环变量,$loop->iteration 用于具体情况。 https://laravel.com/docs/5.3/blade#the-loop-variable
Exapmle:
例子:
@foreach ($questions as $question)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>{{ $question->question }}</td>
<td>{{ $question->category_id }}</td>
</tr>
@endforeach
回答by Shubham Bansal
Add a key value in the foreach loop
在 foreach 循环中添加键值
@foreach($questions as $key => $question)
<tr>
<th scope="row">{{ ++$key }}</th>
<td>{{ $question->question }}</td>
<td>{{ $question->category_id }}</td>
</tr>
@endforeach
回答by Unni K S
Just use {{ $loop->iteration }} to iterate from 1 to limit
只需使用 {{ $loop->iteration }} 从 1 迭代到限制
@foreach($categories as $category)
<li><a href="#tab_c{{ $loop->iteration }}" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach
回答by Styphon
Just use the key value. For most arrays that will just be 0 up.
只需使用键值。对于大多数只会为 0 的数组。
@foreach($categories as $i => $category)
<li{{ $i == 0 ? ' class="active"' : '' }}><a href="#tab_c{{ $i }}" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach
回答by Hiran D.A Walawage
You can try this:
你可以试试这个:
@php($count=0)
@foreach($unit->materials as $m)
@if($m->type == "videos")
@php($count++)
@endif
@endforeach
{{$count}}