note 42723 added to function.uasort
| From: | marek at lewczuk dot com | Date: | Thu, 27 May 2004 08:01:22 +0000 |
| Subject: | note 42723 added to function.uasort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-70164@lists.php.net to get a copy of this message | ||
Below another array sorting function - you can use many keys, whether order type is ascendant or
descendant, if values of given key should be treat as string or numeric, if array keys should be
preserved. This function is locale-safe - it means that string sorting will be based on setLocale
settings. You should be aware that I did not make comprehensive tests, so be careful...
// my locales
SetLocale(LC_COLLATE,"pl_PL.UTF-8");
SetLocale(LC_CTYPE, "pl_PL.UTF-8");
function Array_Sort ($array, $arguments = Array(), $keys = true) {
// comparing function code
$code = "";
// foreach sorting argument (array key)
foreach ($arguments as $argument) {
// order field
$field = substr($argument, 2, strlen($argument));
// sort type ("s" -> string, "n" -> numeric)
$type = $argument[0];
// sort order ("+" -> "ASC", "-" -> "DESC")
$order = $argument[1];
// add "if" statement, which checks if this argument
should be used
$code .= "if (!Is_Numeric(\$result) || \$result == 0) ";
// if "numeric" sort type
if (strtolower($type) == "n") $code .= $order == "-" ? "\$result =
(\$a['{$field}'] > \$b['{$field}'] ? -1 : (\$a['{$field}'] <
\$b['{$field}'] ? 1 : 0));" : "\$result = (\$a['{$field}'] >
\$b['{$field}'] ? 1 : (\$a['{$field}'] < \$b['{$field}'] ? -1 :
0));";
// if "string" sort type
else $code .= $order == "-" ? "\$result = strcoll(\$a['{$field}'],
\$b['{$field}']) * -1;" : "\$result = strcoll(\$a['{$field}'],
\$b['{$field}']);";
}
// return result
$code .= "return \$result;";
// create comparing function
$compare = create_function('$a, $b', $code);
// sort array and preserve keys
if ($keys) uasort($array, $compare);
// sort array, but not preserve keys
else usort($array, $compare);
// return array
return $array;
}
Example array:
$array['sdsd'] = array("dir" => 1, "name" => "sas",
"olek" => "sdsd");
$array['sds2'] = array("dir" => 2, "name" =>
"śas", "olek" => "t");
Example - preserve keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")));
Array
(
[sds2] => Array
(
[dir] => 1
[name] => śas
[olek] => t
)
[sdsd] => Array
(
[dir] => 1
[name] => sas
[olek] => sdsd
)
)
Example - without preserving keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")),
false);
Array
(
[0] => Array
(
[dir] => 1
[name] => śas
[olek] => t
)
[1] => Array
(
[dir] => 1
[name] => sas
[olek] => sdsd
)
)
Enyoj
----
Manual Page -- http://www.php.net/manual/en/function.uasort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42723
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42723&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42723&report=yes
Search -- http://master.php.net/manage/user-notes.php