note 92222 deleted from function.uasort by danbrown
| From: | danbrown@php.net | Date: | Tue, 14 Jul 2009 23:07:57 +0000 |
| Subject: | note 92222 deleted from function.uasort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158308@lists.php.net to get a copy of this message | ||
Note Submitter: Peter Mugane Kionga-Kamau
----
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;
}