开发者

last entry in a loop

开发者 https://www.devze.com 2023-01-25 07:33 出处:网络
I have an associative array and I generate a lot of different things with this array. The output I need has the form

I have an associative array and I generate a lot of different things with this array.

The output I need has the form

aa, ab, ac, ad, af, ak, az

So the last entry does not have a co开发者_如何学Gomma after it

{section name=i loop=$aColums}
  {if $aColums[i].contshow eq 'y'}
    {$aColums[i].Name}
  {endif}
{/section}

My problem is that I don't know when I've reached the last value, which has the contshow=y attribute. So my next thought was to apply the comma before I write aColums[i].Name. But here I have a similar problem becuase I don't know when I've reached the first value with contshow=y. Does anyone have a suggestion?


There is an alternative method, using the section's .last property.

{section name=i loop=$aColums} 
  {if $aColums[i].contshow eq 'y'} 
    {$aColums[i].Name}{if $smarty.section.i.last eq false}, {/if}
  {endif} 
{/section}

This adds a ', ' after every output Name - unless it's the last iteration of the {section}. I'm assuming that your $aColums array data doesn't already have commas tacked on.

You also have another option - pregenerate this string in PHP using implode:

$aColumsString = implode(', ', $aColums);
$smarty->assign('aColumsString', $aColumsString);

Then just output to the template as needed. If you require the list with commas more than once, this is probably the more efficient method. If you need it once, it's probably a toss-up effiency-wise.


The general way to deal with this is to write the commas before each element. In this way, the special-case is the first element (which doesn't need a preceding comma) rather than the last, and it's a lot easier to work out whether you're seeing the first element or not. Just set a boolean flag to true initially, then set it to false after matching an entry.

Mind you, Smarty might have a utility function for "joining" the array with a given string (comma, in this case). If such a function exists, using it directly would be the best option.


In Smarty 3, this is much simplified:

{foreach $aColumns AS $aCol}
    {$aCol}{if not $aCol@last}, {/if}
{/foreach}
0

精彩评论

暂无评论...
验证码 换一张
取 消