在每个列表项后添加逗号,但仅当列表中有多个项时才添加逗号

在每个列表项后添加逗号,但仅当列表中有多个项时才添加逗号

问题描述:

I have a list of tags that I'm using to filter projects inside a data attribute.

I used split() for my array, however I need to add a comma as a separator if there is more than one item in the list. Ideally this is how I would like it to work.

// Senario 1 – Single item
<a href="#" data-tag="projects">Project Title</a>

// Senario 2 – More than 1 item
<a href="#" data-tag="product,commercial,housing">Project Title</a>

My current code:

<?php foreach($project->tags()->split(',') as $tag): ?>
   <a href="#" data-tag="<?php echo $tag; ?>">Project</a>
<?php endforeach; ?>  

I'm just not sure how to check if I've completed the loop after first.

Thanks for the help.

我有一个标签列表,我用它来过滤数据属性中的项目。 p> \ n

我对我的数组使用了split(),但是如果列表中有多个项目,我需要添加一个逗号作为分隔符。 理想情况下,这就是我希望它工作的方式。 p>

  // Senario 1  - 单项
&lt; a href =“#”data-tag =“projects”&gt; 项目标题&lt; / a&gt; 
 
 // Senario 2  - 超过1个项目
&lt; a href =“#”data-tag =“product,commercial,housing”&gt;项目标题&lt; / a&gt; 
   pre> 
 
 

我当前的代码: p>

 &lt;?php foreach($ project-&gt; tags() - &gt; split  (',')作为$ tag):?&gt; 
&lt; a href =“#”data-tag =“&lt;?php echo $ tag;?&gt;”&gt; Project&lt; / a&gt; 
&lt;  ?php endforeach;  ?&GT;  
  code>  pre> 
 
 

我只是不确定如何检查我是否在第一次完成循环后。 p>

谢谢你 救命。 p> div>

Try implode function. manual

<a href="#" data-tag="<?php echo implode(',', $project->tags()) ?>">Project</a>

Build your string first before adding it into your anchor:

<?php
$result = '';
foreach($project->tags()->split(',') as $tag) {

     $result .= sprintf('%s,', $tag);     
}
//Will remove the last character of the string.
$result = substr($result, 0, -1);
?>

<a href="#" data-tag="<?php echo $result; ?>">Project</a>';