Collator::getSortKey

collator_get_sort_key

文字列のソート用のキーを取得する

説明

オブジェクト指向型

public stringfalse Collator::getSortKey(string $string)

手続き型

stringfalse collator_get_sort_key(Collator $object, string $string)

文字列用の照合キーを返します。 照合キーは文字列のかわりに直接比較することができますが、 これは実装依存の動きであり、ICUライブラリのバージョンによって変わる可能性があります。 一般的に、ソート用のキーはデータベース内部か、関数呼び出しコストがとても高い状況でのみ役に立ちます。

パラメータ

object

Collator オブジェクト。

string

キーの生成元となる文字列。

戻り値

文字列の照合キーを返します。失敗した場合に false を返します

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

例1 collator_get_sort_key の例

<?php
$s1 = 'Hello';

$coll = collator_create('en_US');
$res  = collator_get_sort_key($coll, $s1);

echo bin2hex($res);
?>

上の例の出力は、 たとえば以下のようになります。


3832404046010901dc08

例2 Collator::getSortKeyusort と一緒に使う例

<?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);
?>

上の例の出力は、 たとえば以下のようになります。


array(3) {
[0] =>
array(2) {
'name' =>
string(25) "🇳🇱 Derick Rethans"
'linked_account' =>
string(33) "https://phpc.social/users/derickr"
}
[1] =>
array(2) {
'name' =>
string(9) "Elephpant"
'linked_account' =>
string(24) "https://phpc.social/phpc"
}
[2] =>
array(2) {
'name' =>
string(25) "🇫🇷 Marcus Bointon"
'linked_account' =>
string(33) "https://phpc.social/users/Synchro"
}
}

参考

  • collator_sort
  • collator_sort_with_sort_keys