2024 日本 PHP 研討會

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::asort -- collator_asort排序陣列並維持索引關聯

說明

物件導向風格

public Collator::asort(陣列 &$array, 整數 $flags = Collator::SORT_REGULAR): 布林值

程序式風格

collator_asort(Collator $object, 陣列 &$array, 整數 $flags = Collator::SORT_REGULAR): 布林值

此函式排序陣列,使陣列索引保持與其關聯的陣列元素的相關性。這主要用於排序關聯式陣列,其中實際元素順序很重要。陣列元素將根據目前的語系規則進行排序。

等同於標準 PHP 的 asort() 函式。

參數

object

Collator 物件。

array

要排序的字串陣列。

flags

可選的排序類型,下列其中之一

預設的 flags 值為 Collator::SORT_REGULAR。如果指定了無效的 flags 值,也會使用此值。

傳回值

成功時傳回 true,失敗時傳回 false

範例

範例 #1 collator_asort() 範例

<?php
$coll
= collator_create( 'en_US' );
$arr = array(
'a' => '100',
'b' => '50',
'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>

以上範例會輸出

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

另請參閱

新增註解

使用者貢獻的註解 1 則註解

alix dot axel at NOSPAM dot gmail dot com
13 年前
對於那些正在尋找將自然排序與 UCA 規則整合的方法的人來說,這個技巧似乎有效

<?php

$array
= array(
'1', '100',
'al', 'be',
'Alpha', 'Beta',
'Álpha', 'Àlpha', 'Älpha',
'かたかな',
'img1.png', 'img2.png',
'img10.png', 'img20.png'
);

echo
'<pre>';
print_r(sortIntl($array, true));
echo
'</pre>';

function
sortIntl($array, $natural = true)
{
$data = $array;

if (
$natural === true)
{
$data = preg_replace_callback('~([0-9]+)~', 'natsortIntl', $data);
}

collator_asort(collator_create('root'), $data);

return
array_intersect_key($array, $data);
}

function
natsortIntl($number)
{
return
sprintf('%032d', $number);
}

?>
輸出結果

陣列
(
[0] => 1
[1] => 100
[2] => al
[3] => be
[4] => Alpha
[5] => Beta
[6] => Álpha
[7] => Àlpha
[8] => Älpha
[9] => かたかな
[10] => img1.png
[11] => img2.png
[12] => img10.png
[13] => img20.png
)
To Top