按foreach中的第一个字符对行进行分组

时间:2014-05-07 08:26:22

标签: php smarty

我有foreach循环

{foreach from=$rootCategories item=category}
    <li id="parentCategory" data-category="{$category.id_category}">
        <span>
            <img alt="{$category.name}" src="{$base_dir}img/c/{$category.id_category}.jpg" width='46' height='26'>
            <h1>{$category.name}</h1>
        </span>
    </li>                               
    {/foreach}

当前输出为:

Ajp Alter beta black cpanle cupa

我希望它是

A Ajp Alter
B beta black
C cpanle cupa

我在foreach

中使用了该代码
$lastFoundLetter = ''; 
$firstLetter = {$category.name|substr:0:1} 
{if {$firstLetter} != {$lastFoundLetter}} //you've started a new letter category
 {if {$lastFoundLetter} != ''} //if there's a real value in $lastFoundLetter, we need to close the previous div </div>
 {/if } 
<div id="{$firstLetter}"> {$firstLetter} "<br/>"
{ $lastFoundLetter} = {$firstLetter}; </div> 
{/if}

但它不起作用我认为我使用了错误的代码。人们帮助我

2 个答案:

答案 0 :(得分:0)

该代码可以满足您的需求:

{assign  var = 'lastFoundLetter' value= ''}
{foreach from=$rootCategories item=category}
{assign  var = 'curFirstLetter' value= {$category.name|substr:0:1|upper}}

{if $curFirstLetter neq $lastFoundLetter} 
    {$curFirstLetter}
    {assign  var = 'lastFoundLetter' value=$curFirstLetter} 
    {$category.name}
{else}
     &nbsp; &nbsp;{$category.name}
{/if}

<br />
{/foreach}

在最新的Smarty 3.1.18中进行了测试

此代码的结果是:

A Ajp
  Alter
B beta
  black
C cpanle
  cupa 

所以你想要的一样

答案 1 :(得分:0)

更改问题的代码:

{assign  var = 'lastFoundLetter' value= ''}
{foreach from=$rootCategories item=category}
{assign  var = 'curFirstLetter' value= {$category.name|substr:0:1|upper}}

{if $curFirstLetter neq $lastFoundLetter} 
    {if $lastFoundLetter neq ''}<br />{/if}
    {$curFirstLetter}
    {assign  var = 'lastFoundLetter' value=$curFirstLetter} 
{/if}
{$category.name}
{/foreach}