Laravel 4 adding numbers from foreach loop when co

2019-02-12 03:29发布

I am passing the array $cats to my laravel template view. It is a multidimensional array from a database transaction, containing category data. So it would contain data like:

$cat[0]['id'] = 1;
$cat[0]['name'] = 'First Category';

And so on. In my blade template I have the following code:

            {{ $i=0 }}
            @foreach($cats as $cat)

                    {{ $cat['name'] }}<br />

                {{ $i++ }}

            @endforeach

Which outputs:

0 First Category
1 Second Category
2 Third Category

Notice the numbers preceding the category name. Where are they coming from? Is this some clever Laravel trick? It seems that when you include a counter variable, they are automatically added. I can't find any mention of it anywhere, and I don't want them! How do I get rid of them?

Thanks.

标签: laravel-4
5条回答
叼着烟拽天下
2楼-- · 2019-02-12 04:02

You can actually use a built in helper for this: {{ $cat->incrementing }}.

查看更多
叛逆
3楼-- · 2019-02-12 04:06

The {{ }} syntax in blade essentially means echo. You are echoing out $i++ in each iteration of your loop. if you dont want this value to echo you should instead wrap in php tags. e.g.:

<?php $i=0 ?>

@foreach($cats as $cat)
    {{ $cat['name'] }}<br />
<?php $i++ ?>
@endforeach

As an additional note, if you choose to work in arrays then thats your call but unless you have a specific reason to do so I would encourage you to work with object syntax, eloquent collection objects in laravel can be iterated over just like arrays but give you a whole lot of extra sugar once you get used to it.

查看更多
甜甜的少女心
4楼-- · 2019-02-12 04:08
<? php $i = 0 ?>
@foreach ( $variable_name as $value )
    {{ $ value }}<br />
< ? php $i++ ?>
@endforeach
查看更多
可以哭但决不认输i
5楼-- · 2019-02-12 04:12

You just need to use the plain php translation:

@foreach ($collection as $index => $element)
   {{$index}} - {{$element['name']}}
@endforeach

EDIT:

Note the $index will start from 0, So it should be {{ $index+1 }}

查看更多
我命由我不由天
6楼-- · 2019-02-12 04:15
@foreach($cats as $cat)
    {{ (isset($i))?$i++:($i = 0) }} - {{$cat['name']}}
@endforeach
查看更多
登录 后发表回答