note 92223 deleted from function.usort by danbrown
| From: | danbrown@php.net | Date: | Tue, 14 Jul 2009 23:07:47 +0000 |
| Subject: | note 92223 deleted from function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158307@lists.php.net to get a copy of this message | ||
Note Submitter: Peter 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
usort() function *do not* work. usort() 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_SORT(&$a,$k,$d=false)
{ // sorts a 2-d array by key $k, *maintaining orignial order* of equal items ($d=sort descending)
// *DOES NOT maintain associations!* To maintain associations, see SUBKEY_ASORT()
//
// © 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_SORT($people,"fname");
// SUBKEY_SORT($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[] = $a[$w]; // pass 2: populate sorted array
return $a=$t;
}