【问题标题】:How to find last index of foreach loop in smarty如何在 smarty 中找到 foreach 循环的最后一个索引
【发布时间】:2011-03-08 06:36:33
【问题描述】:

如何在 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}

我希望当他们是最后一个城市名称之后它是水平线,否则它就像印度-美国-日本-但最后它是日本-中国

在.php中我使用

<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;

query to find citylist
$main_smarty->assign('cityList',$cityList);
?>

【问题讨论】:

  • 请提供更多代码,以便我们确定问题所在,您提供的 sn-p 在我看来没问题,应该可以正常工作

标签: php smarty


【解决方案1】:

如果 $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}
    

    【讨论】:

      【解决方案3】:

      你正在寻找这个:

      {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 是您的对象的名称。

      【讨论】:

      • 这里的 $smarty 是什么,我可以在那个地方使用其他东西,比如我使用 $main_smarty 在 .php 中我分配 $main_smarty->assign('cityList',$cityList);
      • 据我所知,{$smarty} 是一个保留变量,您应该使用它。如果您的 php 对象名称不同,则无关紧要。你可以在这里找到更多关于{$smarty}的信息:smarty.net/manual/en/language.variables.smarty.php
      • 他们还有其他方法可以找到它
      【解决方案4】:

      这实际上对我有用:

      {$myvar=$someArray@end}
      {$myvar.someproperty}
      

      【讨论】:

        【解决方案5】:

        我认为较新版本的 Smarty 解决此问题的技术比其他答案显示的要新。 latest docs 中的示例(在撰写本文时)正在使用 @last-property。你可以这样使用它:{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}
        

        【讨论】:

          【解决方案6】:

          我的解决方案:

          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
          

          【讨论】:

          • 最后一项:{if $key &gt;= ($interest|count - 1)}.{/if}
          猜你喜欢
          • 2013-10-16
          • 1970-01-01
          • 2020-10-08
          • 2018-11-03
          • 1970-01-01
          • 1970-01-01
          • 2018-11-03
          • 2015-12-03
          • 1970-01-01
          相关资源
          最近更新 更多