2010-06-25 71 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