使用'和'结束一个聪明的foreach循环

时间:2015-09-16 07:41:25

标签: php foreach smarty

我从一个数组中提取一个名单和日期列表,我希望将其作为一个自然语言句子呈现,倒数第二个项目后跟'和',然后是最后一项。

这是我的代码:

<p>In the past, we&rsquo;ve interviewed the likes of {foreach from=$interviewees key=k item=v name=people}
<a href="https://www.example.com/interviews/{$v}.html">{$k}</a
{if $smarty.foreach.people.last}. {else},{/if} {foreachelse}{/foreach}

其中key是人名,item是日期(201509)形式的url。这会输出一个很好的逗号分隔列表,但如何插入自然的外观并完成列表?

我希望得到以下输出:

<p>In the past, we&rsquo;ve interviewed the likes of 
<a href="https://www.example.com/interviews/201405.html">Forename Surname</a>,  
<a href="https://www.example.com/interviews/201408.html">Forename Surname</a>,  
<a href="https://www.example.com/interviews/201403.html">Forename Surname</a> 
and  <a href="https://www.example.com/interviews/201312.html">Forename Surname</a>.

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

试试这个:

<p>In the past, we&rsquo;ve interviewed the likes of {foreach     
from=$interviewees key=k item=v name=people}
{if $smarty.foreach.people.last} and {/if}
<a href="https://www.example.com/interviews/{$v}.html">{$k}</a>
{if $smarty.foreach.people.last}.{else}
   {if $smarty.foreach.people.iteration+1!=$smarty.foreach.people.total},{/if}  
{/if} {foreachelse}{/foreach}