note 44790 deleted from function.usort by tomsommer
| From: | tomsommer@php.net | Date: | Mon, 16 Aug 2004 19:33:54 +0000 |
| Subject: | note 44790 deleted from function.usort by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-74774@lists.php.net to get a copy of this message | ||
Note Submitter: andreaskalsch at gmx dot de
----
The problem with sort() (for example) is that this function is not a friend of the special
characters like 'Ä', 'â' or 'ß', characters that are used in other
languages than English. They are NOT valued like the normal ones, like 'A', 'a'
or 'ss'.
With this small script you can compare the different sort functions. The last one is a usort() one
where I have included an own sort function, that equals upper and lower case AND some characters
like 'ä' and 'a':
<? $a = array('Ben', -1, 2.5, -2.4, 0, 234.4, '*Änni', 'Anni',
'(Becker Yvonne)', 'Beckerts', 'Anna M.', 'Anna',
'anna', 'Annâ', 'Anna-Maria', 'Annamaria',
'+August', 'zorro'); ?>
<table border=0 cellspacing=0 cellpadding=10>
<tr>
<td>
<b>[unsortiert]:</b><br> <br>
<? print_array($a); ?>
</td>
<td>
<b>sort($a):</b><br> <br>
<? sort($a); print_array($a); ?>
</td>
<td>
<b>sort($a, SORT_NUMERIC):</b><br> <br>
<? sort($a, SORT_NUMERIC); print_array($a); ?>
</td>
<td>
<b>sort($a, SORT_STRING):</b><br> <br>
<? sort($a, SORT_STRING); print_array($a); ?>
</td>
<td>
<b>asort($a):</b><br> <br>
<? asort($a); print_array($a); ?>
</td>
<td>
<b>natsort($a):</b><br> <br>
<? natsort($a); print_array($a); ?>
</td>
<td>
<b>usort ($a, "cmp"):</b><br> <br>
<?
function simplify_char($c)
{
$c = strtolower($c);
$cs = array('' => array('!', '"', '/',
'(', ')', '=', '?', '+', '*',
'\'', '#', '|', ',', '.', ':',
'-', '_'),
'a' => array('à', 'á', 'â',
'ã', 'ä', 'å'),
'ae' => array('æ'),
'c' => array('¢', 'ç'),
'd' => array('ð'),
'e' => array('è', 'é', 'ê',
'ë'),
'i' => array('í', 'î', 'ï',
'ì'),
'n' => array('ñ'),
'o' => array('', 'ò', 'ó',
'ô', 'õ', 'ö', 'ø'),
'oe' => array(''),
'p' => array('þ'),
's' => array(''),
'ss' => array('ß'),
'u' => array('ù', 'ú', 'û',
'ü'),
'y' => array('ý', 'ÿ'));
foreach ($cs as $sc => $ncs)
{
foreach ($ncs as $nc) $c = str_replace($nc, $sc, $c);
}
return $c;
}
function cmp ($a, $b)
{
$a = simplify_char($a);
$b = simplify_char($b);
if ($a == $b) return 0;
else return ($a < $b) ? -1 : 1;
}
usort ($a, "cmp"); print_array($a);
?>
</td>
</tr>
</table>
<?
function print_array($a)
{
foreach ($a as $n => $p) echo $n, ' : ', htmlentities($p), '<br>';
}
?>
You can see that ' ' is NOT replaced by '', so family names are sorted first.
Pay attention: Minus numbers are NOT sorted in the normal way because '-' is replaced by
''.