2017-02-11 59 views
-1

我想格式化SQL結果以按第一個字符列出sql條目(以所有數字一起開始ASC,然後從A開始,然後從B開始,然後從C開始) 。但我也希望每個角色都有自己的部分。MYSQLi按第一個字符排序並將結果拆分爲部分

例:

# 

123 Company 
21st Century 
45th Avenue 
99th whatever 

A 

Aerosmith 
Animal 
Apple 

B 

Bat 
Binary 
Bishop 


etc. 

我寧願如果可能這樣做的一個查詢。我只是不知道如何設置這樣的東西。

+1

入住PHP的首字母在每次迭代。 – chris85

+0

你可以幫助一個代碼示例嗎?我不知道如何寫這個是有效的 – KDJ

+1

作爲答案發布。 – chris85

回答

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

+0

完美工作!謝謝! – KDJ

+0

我有另一個問題把它帶到另一個層面。 http://stackoverflow.com/questions/42180469/how-do-i-combine-numbers-into-one-group – KDJ

相關問題