Create comma separated list from array in laravel/blade?

落花浮王杯 提交于 2019-12-23 07:48:20

问题


I am displaying elements of an array @foreach($tags as $tag)$tag->@endforeach. The output is tag1tag2tag3. What is the possible way to sho elements of array in tag1,tag2,tag3. And how to not show, if there is only one element in array.


回答1:


implode() is good for echoing simple data. In real project you usually want to add some HTML or logic into the loop, use $loop variable which is available since 5.3:

@foreach ($arrayOrCollection as $value)
    {{ $loop->first ? '' : ', ' }}
    <span class="nice">{{ $value->first_name }}</span>
@endforeach



回答2:


The selected answer is too complicated. Laravel has a simpler solution:

{{ $items->pluck('tag')->implode(', ') }}



回答3:


Use implode:

{{ implode(', ', $tags) }}



回答4:


implode is one option or you can using join as well like this

{{ join(', ', $tags) }} 

Try the first one or this one.. good luck




回答5:


Try implode():

$arr = ['one', 'two', 'three'];
echo implode(',', $arr);

// output

one,two,three



回答6:


I believe what you are looking for might be something like this: //have your array in php tags //$arr = ['one', 'two', 'three']; ? > //go through the array with foreach and if the count of the array is not equal to the las element then put coma after it

@foreach ($arr as $key => $value)
    @if( count( $arr ) != $key + 1 )
        {{ $value }},
     @else
        {{ $value }}
    @endif
@endforeach


来源:https://stackoverflow.com/questions/40673923/create-comma-separated-list-from-array-in-laravel-blade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!