php Smarty 如何从 foreach 获取第一个索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14056545/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:32:15  来源:igfitidea点击:

Smarty how to get a first index from foreach?

phpforeachsmarty

提问by Marius

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 optionselemets has a $limit value. How to make it good? I need only first one.

但它出错了。在这种情况下,所有options元素都有一个 $limit 值。怎样才能做得好?我只需要第一个。

回答by hdvianna

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.

我不想显得粗鲁,但邦迪的回答并非在所有情况下都有效。由于 PHP 的数组是有序映射,因此第一个键的值不会总是 0。

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

在这些情况下,您可以使用@index,@iteration@first属性。更多细节foreachhttp://www.smarty.net/docs/en/language.function.foreach.tpl#foreach.property.iteration的 smarty文档中

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}

回答by 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}

回答by Ron van der Heijden

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}