【问题标题】:PHP - Group rows by the first letter [closed]PHP - 按第一个字母分组行[关闭]
【发布时间】:2012-04-04 10:35:27
【问题描述】:

我试图以一种有条理和清晰的方式显示我的数据库中的一些元素,但我找不到合适的解决方案。假设我在 db 中有这些行:apple、anchor、beat、cover、classmate、screen... 我需要像这样显示它们:

A
apple
anchor

B
beat

C
cover
classmate
curtain

因此,根据单词的第一个字母,有不同的 div 和不同的类。我可以使用 mysql 查询创建一个类来选择像 $char 这样的名称,其中 $char 是一个参数,然后按 A-Z 时间重复该类......但我不喜欢这样,因为手动工作太多。你有什么建议吗?

【问题讨论】:

    标签: php mysql string select indexing


    【解决方案1】:

    您希望列表完全按字母顺序排列吗?还是仅按首字母分组?您是否关心不以您的任何单词开头的字母是否不显示为标题?例如,如果您没有任何以“x”开头的单词,您是否仍然需要看到下面没有任何内容的“X”类别,还是应该从“W”跳到“Y”?

    具体实施可能会因这些问题的答案而异。这是一个应该完全按字母顺序显示列表的解决方案,跳过其中没有单词的类别。 (不确定你想要什么样的标记;这是非常简单的)。

    $result = mysql_query("SELECT col FROM table ORDER BY col");
    $lastFoundLetter = '';
    while($row = mysql_fetch_array($result)) {
        //get the first letter of the current record
        $firstLetter = substr($row['col'], 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 
                echo "</div>";
            }
            echo "<div id='" . strtoupper($firstLetter) . "'>";
            echo strtoupper($firstLetter) . "<br/>";
            $lastFoundLetter = $firstLetter;
        }
        echo $row['col']. "<br/>";
    }
    //close the last div
    if ($lastFoundLetter != '') {
        echo "</div>";
    }
    

    【讨论】:

      【解决方案2】:

      这样的东西应该可以工作。

      <?php
      $words = $db->query("select word from table order by word")->fetchAll(PDO::FETCH_COLUMN);
      $groups = array();
      
      foreach($words as $word) {
          $groups[$word[0]][] = $word;
      }
      
      foreach(range('a', 'z') as $c) {
          echo $c . "\n";
          foreach($words[$c] as $word) {
              echo $word . "\n";
          }
      }
      

      【讨论】:

        【解决方案3】:

        我将使用单个查询将所有单词(当然是排序的)读入 PHP 数组。然后使用一些 PHP 代码,您可以将它们从数组中拉出,根据需要插入前导字母“A”、“B”。

        【讨论】:

        • 谢谢杰!你的建议对我有帮助。我使用了 for 遍历数组并检查项目的第一个字母是否与前一个项目的第一个字母不同。
        【解决方案4】:

        将它们按字母顺序排列,然后在打印时跟踪您所在的字母。当您找到一个新字母时,在继续之前打印一个新的标题。

        【讨论】:

          猜你喜欢
          • 2022-05-22
          • 1970-01-01
          • 2016-09-15
          • 2022-11-22
          • 2021-02-18
          • 2011-03-22
          • 1970-01-01
          • 2022-01-01
          • 1970-01-01
          相关资源
          最近更新 更多