如何在smarty中找到foreach循环的最后一个索引

Bha*_*dey 17 php smarty

如何在smarty中获取foreach循环的最后一个索引值,对于smarty我是新的,我已经使用了这个代码,但它不起作用

{foreach from=$cityList key=myId item=i name=foo}
 {$i.location_name}{if $main_smarty.foreach.foo.last}<hr>{else}-{/if}
  {/foreach}
Run Code Online (Sandbox Code Playgroud)

我想要的是,当它们是最后一个城市名称之后它的水平线,否则它就像印度 - 美国 - 日本 - 但最后它来到日本 - 中国

在.php我用

<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;

query to find citylist
$main_smarty->assign('cityList',$cityList);
?>
Run Code Online (Sandbox Code Playgroud)

Bog*_*scu 25

你正在寻找这个:

{foreach from=$cityList key=myId item=i name=foo}
    {if $smarty.foreach.foo.last}
        <p>This is the last item from the array!</p>
    {/if}
{/foreach}
Run Code Online (Sandbox Code Playgroud)

正如你看到的,你需要检查属性是$smarty.foreach.foo.last哪里foo是你的对象的名称.


Hig*_*lar 5

我认为 Smarty 的新版本有比其他答案显示的更新的技术来解决这个问题。最新文档中的示例(在撰写本文时)正在使用 -property @last。您可以像这样使用它:{if $item@last}...
完整示例:

{* Add horizontal rule at end of list *}
{foreach $items as $item}
  <a href="#{$item.id}">{$item.name}</a>{if $item@last}<hr>{else},{/if}
{foreachelse}
  ... no items to loop ...
{/foreach}
Run Code Online (Sandbox Code Playgroud)