Two managers dating

When trying to do some custom sorting with objects and an anonymous function it wasn't entirely clear how this usort function works.

Also, because robert uses strcasecmp the algorithm doesn't work properly with floats or other variable types.

Here's the improved version: As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field.

In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below.

This is key to getting your logic right in the comparisons.

If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place.

To test I cut down my code to sorting a simple array from highest priority to lowest.

Output:b (8) is higher priority than a (3), moving b up arrayb (5) is higher priority than a (3), moving b up arrayb (7) is higher priority than a (3), moving b up arraya (3) is same priority as b (3), keeping the samea (8) is higher priority than b (3), moving b down arrayb (8) is higher priority than a (7), moving b up arrayb (8) is higher priority than a (5), moving b up arrayb (8) is higher priority than a (3), moving b up arraya (5) is higher priority than b (3), moving b down arraya (7) is higher priority than b (5), moving b down array Sorted priorities:array(5) { [0]= I wrote a wrapper for usort that lets you use something similar to an SQL ORDER BY clause.

It can sort arrays of associative arrays and arrays of objects and I think it would work with some hybrid case.

Example of how the function works: To sort an array of objects you would do something like: Utility::order By($object Ary, 'get Creation Date() DESC, get Sub Order() ASC'); This would sort an array of objects that have methods get Creation Date() and get Sub Order().

Here is the function: /* * @param array $ary the array we want to sort * @param string $clause a string specifying how to sort the array similar to SQL ORDER BY clause * @param bool $ascending that default sorts fall back to when no direction is specified * @return null */ The array_alternate_multisort function written by robert below doesn't work.

There are several bugs in the code and it doesn't work when sorting by multiple keys because the order of the first key isn't taken into account when sorting by the second key and so on.

Tags: , ,