|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-12-07 03:38 UTC] shabbir dot bhojani at objectsynergy dot com
Description:
------------
Doesn't sort correctly. I'm attempting to sort so that the values 'c' and 'd' show
up on the top in that order followed by the other values sorted using strcasecmp.
'c' and 'd' do show up on the top of the sorted array but not in that order.
Test script:
---------------
$x = array('a','b','c','d','e','f');
usort($x, function ($a, $b) {
// must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second
static $custom_sort_data = array(
'c' => 256,
'd' => 255,
);
if (isset($custom_sort_data[$a]))
return -$custom_sort_data[$a];
if (isset($custom_sort_data[$b]))
return $custom_sort_data[$b];
return strcasecmp($a, $b);
});
var_dump($x);
Expected result:
----------------
array(6) { [0] => string(1) "c" [1] => string(1) "d" [2] => string(1) "a" [3] =>
string(1) "b" [4] => string(1) "e" [5] => string(1) "f" }
Actual result:
--------------
array(6) { [0] => string(1) "d" [1] => string(1) "c" [2] => string(1) "a" [3] =>
string(1) "b" [4] => string(1) "e" [5] => string(1) "f" }
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Dec 11 04:00:01 2025 UTC |
My mistake: "usort() doesn't pay attention to the magnitude of the return value.". For the record, this solved it for me: $x = array('a', 'b', 'c', 'd', 'e', 'f'); usort($x, $y = function ($a, $b) { // must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second static $custom_sort_data = array( 'c' => 256, 'd' => 255, ); if (isset($custom_sort_data[$a]) && isset($custom_sort_data[$b])) { return $custom_sort_data[$b] - $custom_sort_data[$a]; } if (isset($custom_sort_data[$b])) return 1; if (isset($custom_sort_data[$a])) return -1; return strcasecmp($a, $b); }); var_dump($x);