Smarty how to get a first index from foreach?

限于喜欢 提交于 2019-12-07 02:59:21

问题


Construction is this:

<!-- projects list -->
            {if !empty($userObjects)}
                <select id="projects-list" tabindex="1" name="project">
                    {if !isset($selected)}<option value="0">Choose project</option>{/if}
                {foreach from=$userObjects item=v}
                    <option value="{$v.Id}" {if $selected==$v.Id}selected="selected"{/if} }>{$v.Name}

                        {* if it's 1st element *}
                        {if $smarty.foreach.v.index == 0}
                            {if isset($limit)}<br /><span id="projlimit">{$limit}</span> {$currency->sign}{/if}
                        {/if}

                    </option>
                {/foreach}
                </select>

as you can see I did

{if $smarty.foreach.v.index == 0}

but it's going wrong. In this case all the options elemets has a $limit value. How to make it good? I need only first one.


回答1:


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}



回答2:


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}



回答3:


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}


来源:https://stackoverflow.com/questions/14056545/smarty-how-to-get-a-first-index-from-foreach

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