我研究了關於 `sort()` 函式和德語變音符號的各種問題,很快就讓我頭昏腦脹 —— `sort()` 函式是否有 bug?是否該用 locale 解決?等等...(我是個完全的新手)。
對我來說,顯而易見的解決方案是快速且不完美的:將變音符號(在我的例子中以 HTML 編碼呈現)轉換成其一般對應字元('ä' = 'ae','ö' = 'oe','ü' = 'ue','ß' = 'ss' 等等),排序陣列,然後再轉換回來。但有些情況下,'Mueller' 就是 'Mueller',不需要轉換成 'Müller'。因此,例如,我會將變音符號本身替換成其一般對應字元加上一個字串中其他地方沒有使用的字元(例如 '_'),這樣只有在特定組合時才會轉換回變音符號。
當然,除了 '_' 之外,任何其他字元都可以用作附加字元(會影響排序結果)。我知道我的解決方案很粗糙,可能會導致其他排序問題,但它足以滿足我的需求。
此範例中的 `$dat` 陣列填充了德國城鎮名稱(我實際上使用的是多維陣列 (`$dat[][]`),但為了更容易理解,我簡化了程式碼)。
<?php
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
$dat[$totcnt]=str_replace('ß','ss_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Ä','Ae_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('ä','ae_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Ö','Oe_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('ö','oe_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Ü','Ue_',$dat[$totcnt]);
$dat[$totcnt]=str_replace('ü','ue_',$dat[$totcnt]);
}
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
for($totcnt = 0; $totcnt < $max; $totcnt++){
$dat[$totcnt]=str_replace('ss_','ß',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Ae_','Ä',$dat[$totcnt]);
$dat[$totcnt]=str_replace('ae_','ä',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Oe_','Ö',$dat[$totcnt]);
$dat[$totcnt]=str_replace('oe_','ö',$dat[$totcnt]);
$dat[$totcnt]=str_replace('Ue_','Ü',$dat[$totcnt]);
$dat[$totcnt]=str_replace('ue_','ü',$dat[$totcnt]);
}
?>