从 laravel/blade 中的数组创建逗号分隔列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40673923/
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
Create comma separated list from array in laravel/blade?
提问by Zachary Dale
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.
我正在显示一个数组的元素@foreach($tags as $tag)$tag->@endforeach
。输出是tag1tag2tag3
。在tag1,tag2,tag3
. 以及如何不显示,
数组中是否只有一个元素。
回答by Zentag
The selected answer is too complicated. Laravel has a simpler solution:
选择的答案太复杂了。Laravel 有一个更简单的解决方案:
{{ $items->pluck('tag')->implode(', ') }}
回答by Alexey Mezenin
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:
implode()
适合回显简单数据。在实际项目中,您通常希望在循环中添加一些 HTML 或逻辑,使用$loop
自 5.3 以来可用的变量:
@foreach ($arrayOrCollection as $value)
{{ $loop->first ? '' : ', ' }}
<span class="nice">{{ $value->first_name }}</span>
@endforeach
回答by Mihai Matei
Use implode:
使用内爆:
{{ implode(', ', $tags) }}
回答by Dip
Use this. We can implement it using $loop->last
用这个。我们可以使用$loop->last来实现它
@foreach ($arrayOrCollection as $value)
<span class="nice">
{{ $value->first_name }}
@if( !$loop->last)
,
@endif
</span>
@endforeach
回答by anuraj
implode is one option or you can using join as well like this
implode 是一种选择,或者您也可以像这样使用 join
{{ join(', ', $tags) }}
Try the first one or this one.. good luck
尝试第一个或这个..祝你好运
回答by Mayank Pandeyz
Try implode():
尝试内爆():
$arr = ['one', 'two', 'three'];
echo implode(',', $arr);
// output
// 输出
one,two,three
回答by dexuu
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
我相信你正在寻找的可能是这样的: //在 php 标签中有你的数组 //$arr = ['one', 'two', 'three']; ? > // 使用 foreach 遍历数组,如果数组的计数不等于 las 元素,则在其后放置 coma
@foreach ($arr as $key => $value)
@if( count( $arr ) != $key + 1 )
{{ $value }},
@else
{{ $value }}
@endif
@endforeach