2010-06-25 69 views
14

如何获得在智者foreach循环的最后一个索引值,即时通讯新的Smarty的我已经使用这个代码,但它不工作如何找到foreach循环的最后指数智者

{foreach from=$cityList key=myId item=i name=foo} 
{$i.location_name}{if $main_smarty.foreach.foo.last}<hr>{else}-{/if} 
    {/foreach} 

我想,当他们的是最后一个城市名称这种它来水平线后,否则其如印度 - 美国 - 日本 - 但最后它来到日本,中国

以.php我使用

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

query to find citylist 
$main_smarty->assign('cityList',$cityList); 
?> 
+0

请提供更多的代码,所以我们可以确定问题,您提供的代码段对我来说看起来没问题,应该可以正常工作 – jigfox 2010-06-25 12:52:00

回答

22

您正在寻找这样一条:

{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} 

由于你看,你需要检查的属性是$smarty.foreach.foo.last其中foo是你的对象的名称。

+0

什么是$ smarty这里我可以在那个地方使用其他东西,比如我使用$ main_smarty而且在.php我分配$ main_smarty-> assign('cityList',$ cityList); – 2010-06-25 13:33:34

+0

据我所知,'{$ smarty}'是一个保留变量,你应该使用它。如果你的php对象命名不同,这应该没关系。你可以在这里找到关于'{$ smarty}'的更多信息:http://www.smarty.net/manual/en/language.variables.smarty.php – 2010-06-25 13:44:35

+1

我使用了$ smarty,但它不工作 – 2010-06-25 13:52:10

4

如果$ ARR是数组你传递给{foreach},这个将这样的伎俩:

{$arr|@end} 

事实上,它不具有{foreach}中被称为

2
{foreach from=$foo item=$bar name=foo} 
    {if $smarty.foreach.foo.last} 
     Total of({$smarty.foreach.foo.total}) Items <br /> 
     Data ({$bar}) 
    {/if} 
{/foreach} 
2

我认为Smarty的较新版本的解决这个问题比其他的答案显示的新技术。 latest docs(撰写本文时)的示例使用@last属性。您可以使用它是这样的:{if [email protected]}...
完整的示例:

{* Add horizontal rule at end of list *} 
{foreach $items as $item} 
    <a href="#{$item.id}">{$item.name}</a>{if [email protected]}<hr>{else},{/if} 
{foreachelse} 
    ... no items to loop ... 
{/foreach} 
0

我的解决办法:

PHP

Array 
(
    [0] => car 
    [1] => toy 
    [2] => cat 
    [3] => gun 
    [4] => dog 
) 

.tpl

{foreach from=$interest key=$key item=$item} 
    {$item.value}{if $key < ($interest|count - 1)}, {/if} 
{/foreach} 

结果

My interest: 
car, toy, cat, gun, dog 
+0

最后一项:'{if $ key> =($ interest | count - 1)}。{/ if}' – 2016-10-31 21:23:06