Sort array by values in PHP mantaining relative positions -
i'm using usort() , uasort(). need sort array values using user-defined comparison function.
php.net/manual/en/function.usort.php
the doc says: note:
if 2 members compare equal, relative order in sorted array undefined.
the question is: there php function mantain relative position of equal elements?
the short answer php not have built in function this, have write one. of time, not matter if sort moves element or down if considered equal adjoining element. example array of integers. if 2 same, cares order in long together.
for cases need maintain order of lists, sreid has written function this. on usort page @ php.net. pasting here convenience. aware giving sreid full credit code, , have mentioned original code can found in public forum:
function mergesort(&$array, $cmp_function = 'strcmp') { // arrays of size < 2 require no action. if (count($array) < 2) return; // split array in half $halfway = count($array) / 2; $array1 = array_slice($array, 0, $halfway); $array2 = array_slice($array, $halfway); // recurse sort 2 halves mergesort($array1, $cmp_function); mergesort($array2, $cmp_function); // if of $array1 <= of $array2, append them. if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) { $array = array_merge($array1, $array2); return; } // merge 2 sorted arrays single sorted array $array = array(); $ptr1 = $ptr2 = 0; while ($ptr1 < count($array1) && $ptr2 < count($array2)) { if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) { $array[] = $array1[$ptr1++]; } else { $array[] = $array2[$ptr2++]; } } // merge remainder while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++]; while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++]; return;
}
Comments
Post a Comment