将MySQL组合成PHP中的A-Z块

时间:2015-06-10 11:46:40

标签: 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>';
?>

2 个答案:

答案 0 :(得分:2)

按名称排序并逐个处理每个字母。

$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>';
}

答案 1 :(得分:1)

我会这样做可读方式

$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');

$groups = array();

将结果拆分为群组

while ($row = mysql_fetch_assoc($get_az)) {
    $firstLetter = strtolower(substr($row['custom_22'], 0, 1));

检查数字

    if (is_numeric($firstLetter)) {
        $firstLetter = '0-9';
    }

    if (isset($groups[$firstLetter]) === false) {
        $groups[$firstLetter] = array();
    }

    $groups[$firstLetter][] = $row['custom_22'];
}

简单地遍历群组并回应它

foreach ($groups as $h1 => $items) {
    echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
    echo '<ul>';
        foreach ($items as $item) {
            echo sprintf('<li>%s</li>', htmlspecialchars($item));
        }
    echo '</ul>';
}