Forum PHP 2025

Collator::getSortKey

collator_get_sort_key

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 1.0.3)

Collator::getSortKey -- collator_get_sort_key文字列のソート用のキーを取得する

説明

オブジェクト指向型

public Collator::getSortKey(string $string): string|false

手続き型

collator_get_sort_key(Collator $object, string $string): string|false

文字列用の照合キーを返します。 照合キーは文字列のかわりに直接比較することができますが、 これは実装依存の動きであり、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::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);
?>

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


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"
}
}

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top