note 92223 added to function.usort

From: Date: Tue, 14 Jul 2009 22:43:35 +0000
Subject: note 92223 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-158306@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 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; } ---- Server IP: 208.69.120.35 Probable Submitter: 24.125.39.192 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/92223 Del: integrated -- https://master.php.net/note/delete/92223/integrated Del: useless -- https://master.php.net/note/delete/92223/useless Del: bad code -- https://master.php.net/note/delete/92223/bad+code Del: spam -- https://master.php.net/note/delete/92223/spam Del: non-english -- https://master.php.net/note/delete/92223/non-english Del: in docs -- https://master.php.net/note/delete/92223/in+docs Del: other reasons-- https://master.php.net/note/delete/92223 Reject -- https://master.php.net/note/reject/92223 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158306) next »