将PHP结果分组到名字的第一个字母

时间:2011-07-20 10:08:24

标签: php mysql

我有一个查询,它获取last_name排序的所有记录。现在我想创建一个循环,将这些结果按姓氏的第一个字母分组,并在组上方显示字母,即

A
-----------
Albert
Alfred

C
-----------
Charles

D
-----------
Delta etc...

谢谢!

6 个答案:

答案 0 :(得分:10)

lastname方按MySQL订购结果,并跟踪PHP方的第一个字母的更改:

<?php

$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");

while ($rec = mysql_fetch_assoc($rs)) {
    if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
        $initial = strtoupper(substr($rec['lastname'], 0, 1));
        print "$initial\n";
    }
    print $rec['lastname'] . "\n";
}

?>

答案 1 :(得分:4)

$letter = null;
foreach ($array as $word) {
  if ($letter != $word[0]) {
    $letter = $word[0];
    echo '<b>'.strtoupper($word[0]) . '</b><br/>';
  }
  echo strtoupper($word) . '<br/>';
}

并浏览查询添加行:

order by `your_field` asc

答案 2 :(得分:3)

Allready已尝试过这样的事情了吗?

$last = '';
foreach($data as $key=>$row){
    if(substr($row['last_name'],0,1)!=$last) echo '<br /><br />'.substr($row['last_name'],0,1).'<br />----------------<br />';
    $last = substr($row['last_name'],0,1);
    echo $row['last_name'];
}

答案 3 :(得分:2)

在您的视图中,您可以循环记录并将其拆分:

$current = '';
foreach ($rows as $r) {
    if (!$current || strtolower($r['name'][0]) != $current) {
        $current = strtolower($r['name'][0]);
        echo strtoupper($current).'<br />---------------';
    }
    echo $row['name'].'<br />';
}

答案 4 :(得分:0)

在您的查询中,尝试添加以下内容:

group by substr(last_name,1,1)

select substr(last_name,1,1) as alpha, *
from tableName
group by substr(last_name,1,1)

答案 5 :(得分:0)

是的,您可以使用MySql本身

来实现此目的

在我的情况下,brand_name将按照您的预期列出。

示例:

SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != ''  group by alpha
UNION
SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != '' order by brand_name COLLATE NOCASE

结果:

    A
    A Card
    A Cef
    A Cef O
    B
    Bacticef Tab
    Bacticin
    Bactidrox
    Bactidrox Kid
    ........

希望它会对某人有所帮助。