php - 在 PHP 中将 MySQL 结果分组为 A-Z block

标签 php mysql split grouping alphanumeric

我有一个包含数千个结果的列表,我想按字母数字对它们进行分组,例如,我需要它是这样的:

<h1>0-9</h1>
<ul>
  <li>011example</li>
  <li>233example</li>
  <li>65example</li>
</ul>

<h1>A</h1>
<ul>
  <li>albert</li>
  <li>alfred</li>
  <li>annie</li>
</ul>

<h1>B</h1>
<ul>
  <li>ben</li>
  <li>bertie</li>
  <li>burt</li>
</ul>

但我不知道如何将我的结果拆分或分组为 0-9 和 A-Z。

目前我有:

<?php
    $get_az = mysql_query("SELECT custom_22 FROM db_table1");
    echo '<ul>';
        while ($row = mysql_fetch_assoc($get_az)) { 
            $getfirstletter = substr($row['custom_22'], 0,1);
            $name = $row['custom_22'];
            echo '<h1>'.$getfirstletter.'</h1>';
            echo '<li>'.$name.'</li>';
        } 
    echo '</ul>';
?>

最佳答案

按名字排序,一个一个地处理每个字母。

$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) { 
    $first_letter = strtolower(substr($row['custom_22'], 0, 1));
    if (preg_match("/[0-9]/", $first_letter)) { // detect digits
        $first_letter = "0-9";
    }
    if ($first_letter !== $current_first_letter) {
        if ($current_first_letter !== null) {
            echo '</ul>';
        }
        echo '<h1>' . $first_letter . '</h1>';
        echo '<ul>';
    }
    $current_first_letter = $first_letter;
    echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
    echo '</ul>';
}

关于php - 在 PHP 中将 MySQL 结果分组为 A-Z block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755398/

相关文章:

php - 通知系统无法正常工作 JSON/PHP

c++ - boost::split 仅当 C++ 中存在分隔符时才进行拆分

php - Ajax 发布错误加载页面

php - 想要在页面重新加载和页面刷新时显示新上传的图像

php - 使用 Drupal 的在线体育博彩网站

mysql - 在 MySQL 中检索具有层次结构的数据

javascript - jquery给字符串加1

python - 如何在 python 中逐个字符地拆分 unicode 字符串?

php - 添加 "sDom"后数据表未加载数据

php - 有没有更好的方法从 MySQL 数据库获取项目?