MYSQLi按第一个字符排序并将结果拆分为多个部分

时间:2017-02-11 16:17:08

标签: php mysql

我想格式化SQL结果以按第一个字符列出sql条目(从所有数字开始一起ASC,然后从A开始,然后是B,然后是C等)。但我也希望每个角色都有自己的部分。

例如:

#

123 Company
21st Century
45th Avenue
99th whatever

A

Aerosmith
Animal
Apple

B

Bat
Binary
Bishop


etc.

如果可能,我更愿意在一个查询中执行此操作。我不知道如何设置这样的东西。

1 个答案:

答案 0 :(得分:1)

这是一个如何迭代数组并检查第一个字符与前一个字符的示例。如果您的SQL正确排序,那么您应该只需要它。

$last = '';
foreach(array('12', '33 what', '44 more', 'aa', 'ab', 'b', 'c', 'cd', 'd', 'dd') as $words ){
    $current = substr($words, 0, 1);
    if(is_numeric($current)) {
        $current = '#';
    }
    if($current != $last) {
         echo "\n" . strtoupper($current) . "\n\n";
    }
    echo $words . "\n";
    $last = $current;
}

演示:https://eval.in/735196

相关问题