note 92222 added to function.uasort
| From: | PeterMuganeKionga-Kamau at osu1 dot php dot net | Date: | Tue, 14 Jul 2009 22:36:49 +0000 |
| Subject: | note 92222 added to function.uasort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158305@lists.php.net to get a copy of this message | ||
As of PHP 4.1.0: "A new sort algorithm was introduced. The cmp_function doesn't keep the
original order for elements comparing as equal."
So... in case you want to sort a 2-d array by multiple keys in the sub-arrays, multiple calls to the
uasort() function *do not* work. uasort() almost assuredly mixes up the element order from prior
sorts in cases where elements evaluate as equal in the previous call. Below is a function that will
maintain this order:
function SUBKEY_ASORT(&$a,$k,$d=false)
{ // sorts a 2-d array by key $k, *maintaining associations* and
// *maintaining orignial order* of equal items ($d=sort descending)
//
// © 2009 Peter Mugane Kionga-Kamau (http://www.mugane.com)
//
// e.g. to sort a 2-d array of user data ($people) by last name then first name:
// SUBKEY_ASORT($people,"fname");
// SUBKEY_ASORT($people,"lname"); // most relevant key used in the final call.
//
// Free for unrestricted use, as long as this notice remains intact.
//
$u = array(); // stores all unique items:
foreach($a as $x=>$y) $u[(string)$y[$k]][$x]=true; // pass 1: extract unique entries in orignial
order
$d?krsort($u):ksort($u);
$t = array(); // stores sorted array
foreach($u as $p=>$q) foreach($q as $w=>$z) $t[$w] = $a[$w]; // pass 2: populate sorted array
return $a=$t;
}
----
Server IP: 64.71.164.2
Probable Submitter: 24.125.39.192
----
Manual Page -- http://www.php.net/manual/en/function.uasort.php
Edit -- https://master.php.net/note/edit/92222
Del: integrated -- https://master.php.net/note/delete/92222/integrated
Del: useless -- https://master.php.net/note/delete/92222/useless
Del: bad code -- https://master.php.net/note/delete/92222/bad+code
Del: spam -- https://master.php.net/note/delete/92222/spam
Del: non-english -- https://master.php.net/note/delete/92222/non-english
Del: in docs -- https://master.php.net/note/delete/92222/in+docs
Del: other reasons-- https://master.php.net/note/delete/92222
Reject -- https://master.php.net/note/reject/92222
Search -- https://master.php.net/manage/user-notes.php