php 如何在smarty中找到foreach循环的最后一个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3117997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find last index of foreach loop in smarty
提问by Bhanu Prakash Pandey
How to get last index value of foreach loop in smarty,i m new for smarty I have used this code but its not working
如何在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}
i want that when their is last city name after this its come horizontal line otherwise its like india-USA-Japan- but at last it come Japan-china
我希望当他们在这之后是最后一个城市名称时,它是水平线,否则就像印度 - 美国 - 日本 - 但最后它是日本 - china
In .php i use
在 .php 中我使用
<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;
query to find citylist
$main_smarty->assign('cityList',$cityList);
?>
回答by Bogdan Constantinescu
You're looking for this one:
你正在寻找这个:
{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}
As you see, the property you need to check is $smarty.foreach.foo.lastwhere foois the name of your object.
如您所见,您需要检查的属性是对象的名称$smarty.foreach.foo.last在哪里foo。
回答by Lukman
If $arr is the array you passed to the {foreach}, this will do the trick:
如果 $arr 是您传递给 {foreach} 的数组,这将起作用:
{$arr|@end}
In fact, it does not have to be called inside a {foreach}
事实上,它不必在 {foreach} 中调用
回答by Highly Irregular
I think newer versions of Smarty have a newer technique of solving this problem than what the other answers show. The example from the latest docs(at the time of writing) is using the @last-property. You can use it like this: {if $item@last}...
Complete example:
我认为较新版本的 Smarty 具有比其他答案显示的更新的技术来解决这个问题。最新文档中的示例(在撰写本文时)正在使用@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}
回答by RobertPitt
{foreach from=$foo item=$bar name=foo}
{if $smarty.foreach.foo.last}
Total of({$smarty.foreach.foo.total}) Items <br />
Data ({$bar})
{/if}
{/foreach}
回答by jannunen
This actually worked for me:
这实际上对我有用:
{$myvar=$someArray@end}
{$myvar.someproperty}
回答by Patryk Szram
My solution:
我的解决方案:
PHP
PHP
Array
(
[0] => car
[1] => toy
[2] => cat
[3] => gun
[4] => dog
)
.tpl
.tpl
{foreach from=$interest key=$key item=$item}
{$item.value}{if $key < ($interest|count - 1)}, {/if}
{/foreach}
Result
结果
My interest:
car, toy, cat, gun, dog

