note 114535 added to function.uasort

From: Date: Tue, 04 Mar 2014 16:01:00 +0000
Subject: note 114535 added to function.uasort
Groups: php.notes 
Request: Send a blank email to php-notes+get-198786@lists.php.net to get a copy of this message
If you want to keep the order when two members compare as equal, use this. <?php function stable_uasort(&$array, $cmp_function) { if(count($array) < 2) { return; } $halfway = count($array) / 2; $array1 = array_slice($array, 0, $halfway, TRUE); $array2 = array_slice($array, $halfway, NULL, TRUE); stable_uasort($array1, $cmp_function); stable_uasort($array2, $cmp_function); if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) { $array = $array1 + $array2; return; } $array = array(); reset($array1); reset($array2); while(current($array1) && current($array2)) { if(call_user_func($cmp_function, current($array1), current($array2)) < 1) { $array[key($array1)] = current($array1); next($array1); } else { $array[key($array2)] = current($array2); next($array2); } } while(current($array1)) { $array[key($array1)] = current($array1); next($array1); } while(current($array2)) { $array[key($array2)] = current($array2); next($array2); } return; } function cmp($a, $b) { if($a['n'] == $b['n']) { return 0; } return ($a['n'] > $b['n']) ? -1 : 1; } $a = $b = array( 'a' => array("l" => "A", "n" => 1), 'b' => array("l" => "B", "n" => 2), 'c' => array("l" => "C", "n" => 1), 'd' => array("l" => "D", "n" => 2), 'e' => array("l" => "E", "n" => 2), ); uasort($a, 'cmp'); print_r($a); stable_uasort($b, 'cmp'); print_r($b); ?> returns Array ( [e] => Array ( [l] => E [n] => 2 ) [b] => Array ( [l] => B [n] => 2 ) [d] => Array ( [l] => D [n] => 2 ) [c] => Array ( [l] => C [n] => 1 ) [a] => Array ( [l] => A [n] => 1 ) ) Array ( [b] => Array ( [l] => B [n] => 2 ) [d] => Array ( [l] => D [n] => 2 ) [e] => Array ( [l] => E [n] => 2 ) [a] => Array ( [l] => A [n] => 1 ) [c] => Array ( [l] => C [n] => 1 ) ) https://bugs.php.net/bug.php?id=53341 ---- Server IP: 195.139.129.18 Probable Submitter: 79.135.31.13 ---- Manual Page -- http://php.net/manual/en/function.uasort.php Edit -- https://master.php.net/note/edit/114535 Del: integrated -- https://master.php.net/note/delete/114535/integrated Del: useless -- https://master.php.net/note/delete/114535/useless Del: bad code -- https://master.php.net/note/delete/114535/bad+code Del: spam -- https://master.php.net/note/delete/114535/spam Del: non-english -- https://master.php.net/note/delete/114535/non-english Del: in docs -- https://master.php.net/note/delete/114535/in+docs Del: other reasons-- https://master.php.net/note/delete/114535 Reject -- https://master.php.net/note/reject/114535 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198786) next »