note 102542 added to collator.asort

[email protected] Sun, 20 Feb 2011 07:31:15 -0800
Newsgroups php.notes
Message-ID <[email protected]>
For those of you who are looking for a way to integrate natural sorting with the UCA rules this hack seems to work:

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

?>

Output:

Array
(
    [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
)
----
Server IP: 194.8.30.16
Probable Submitter: 178.166.20.43
----
Manual Page -- http://www.php.net/manual/en/collator.asort.php
Edit        -- https://master.php.net/note/edit/102542
Del: integrated  -- https://master.php.net/note/delete/102542/integrated
Del: useless     -- https://master.php.net/note/delete/102542/useless
Del: bad code    -- https://master.php.net/note/delete/102542/bad+code
Del: spam        -- https://master.php.net/note/delete/102542/spam
Del: non-english -- https://master.php.net/note/delete/102542/non-english
Del: in docs     -- https://master.php.net/note/delete/102542/in+docs
Del: other reasons-- https://master.php.net/note/delete/102542
Reject      -- https://master.php.net/note/reject/102542
Search      -- https://master.php.net/manage/user-notes.php