Smarty how to get a first index from foreach?

喜欢而已 提交于 2019-12-05 06:07:21

Could you do this by the array key?

{foreach from=$rows key=i item=row}
     {if $i == 0}
         First item in my array
     {/if}
{/foreach}

I don't want to appear rude, but Bondye's answer will not work in all cases. Since PHP's arrays are ordered maps, the value of the first key will not always be 0.

In these cases you can use the @index, @iteration or @first properties. More details are in the smarty foreach documentation at http://www.smarty.net/docs/en/language.function.foreach.tpl#foreach.property.iteration

One of the possible solutions to your question is bellow:

{foreach $rows as $row}
    {if $row@iteration == 1}
        First item in my array          
    {/if}            
{/foreach}
IT Vlogs

You can use this code:

{foreach from=$userObjects item=v name=obj}

    {if $smarty.foreach.obj.first}
        This is the first item
    {/if}

    {if $smarty.foreach.obj.last}
        This is the last item.
    {/if}
{/foreach}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!