(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 1.0.3)
Collator::getSortKey -- collator_get_sort_key — 文字列のソート用のキーを取得する
オブジェクト指向型
手続き型
文字列用の照合キーを返します。 照合キーは文字列のかわりに直接比較することができますが、 これは実装依存の動きであり、ICUライブラリのバージョンによって変わる可能性があります。 一般的に、ソート用のキーはデータベース内部か、関数呼び出しコストがとても高い状況でのみ役に立ちます。
文字列の照合キーを返します。失敗した場合に false
を返します
例1 collator_get_sort_key() の例
<?php
$s1 = 'Hello';
$coll = collator_create('en_US');
$res = collator_get_sort_key($coll, $s1);
echo bin2hex($res);
?>
上の例の出力は、 たとえば以下のようになります。
例2 Collator::getSortKey() を usort() と一緒に使う例
<?php
$data = [
[ 'name' => '🇳🇱 Derick Rethans', 'linked_account' => 'https://phpc.social/users/derickr' ],
[ 'name' => 'Elephpant', 'linked_account' => 'https://phpc.social/phpc' ],
[ 'name' => '🇫🇷 Marcus Bointon', 'linked_account' => 'https://phpc.social/users/Synchro' ],
];
/* Create the collator */
$col = new Collator('en');
/* Sort upper-case letters before lower-case letters */
$col->setAttribute(Collator::CASE_FIRST, Collator::UPPER_FIRST);
/* Use a user-defined function with sort, that strips out the emojis */
*/
usort(
$data,
function($a, $b) use ($col) {
/* Remove the character class 'S' (the Symbols), and remove whitespace
* (with trim) */
$aName = trim(preg_replace('/\p{S}+/u', '', $a['name']));
$bName = trim(preg_replace('/\p{S}+/u', '', $b['name']));
/* Create the sort key */
$aKey = $col->getSortKey($aName);
$bKey = $col->getSortKey($bName);
/* Use the sort key to signal which element sorts first */
return $aKey <=> $bKey;
}
);
var_dump($data);
?>
上の例の出力は、 たとえば以下のようになります。