按首字母分组,按字母顺序排列,最好的方法是? [英] Group by first letter, alphabetically, best way?

查看:85
本文介绍了按首字母分组,按字母顺序排列,最好的方法是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<div class="widgeter-content no-padding">
    <ul id="contacts">
        <?php
        while ($r = mysql_fetch_array($q)){
            $currentletter = substr($name,0,1);
            if ($currentletter != $lastletter){
            ?>
            <!-- start li data group for specific alphabetic letter -->
            <li data-group="<?=$currentletter;?>">
                <a class="title"><?=strtoupper($currentletter);?></a>
            <?
            }
            ?>
                <ul>
                    <li>
                        <a href="#">
                            <span><?=$name;?></span>
                        </a>
                    </li>
                </ul>
            <?
            if ($currentletter != $lastletter){
            ?>
            </li>
            <!-- end data group (not currently working, ends on first result) -->
            <?
            }
            $lastletter = $currentletter; 
        }
        ?>
    </ul>
</div>

我正在尝试做的事情:

A:

Alfred
Annie

B:

Bob
Billy

如您所见,数据被包装在li数据组中.

As you can see, the data is wrapped in an li data group.

代码的第一部分工作正常,但是最后一部分(我试图将结束li标签放在结束注释之前,在每个循环的第一个结果之后显示,需要在END显示)每个字母的结果).

The first part of the code works perfectly, but the last part (where I'm trying to put the closing li tag before the end comment, shows after the first result of each loop, where it needs to show at the END of each letters results).

做到这一点的最佳方法是什么?我确定我要实现的目标非常明显,但我想不出一种逻辑方法来获取构造我希望的代码.

What would be the best way to do this? I'm sure its quite obvious what I'm trying to achieve but I can't think of a logical way to get the code structuring how I want it to.

谢谢

推荐答案

    $res      = array();
    while ($r = mysql_fetch_array($q)){
      $currentletter = substr($name,0,1);
      $res[$currentletter][]  = $name;
    }

    foreach($res as $key=>$val){
       /// here you add your li
       /// here $key will give you letter and $val will give you name
       echo $key;
       foreach($val as $reqvals){
          echo $reqvals;
          echo "<br>";
       }
    }

这篇关于按首字母分组,按字母顺序排列,最好的方法是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆