I have a problem with PHP usort(). Let’s suppose I have an array like this (that’s a simplification, I’ve not to work with names, and I have an array of objects, not arrays):
$data = array(
array('name' => 'Albert', 'last' => 'Einstein'),
array('name' => 'Lieserl', 'last' => 'Einstein'),
array('name' => 'Alan', 'last' => 'Turing' ),
array('name' => 'Mileva', 'last' => 'Einstein'),
array('name' => 'Hans Albert', 'last' => 'Einstein')
);
As you can see, the array is sorted arbitrarily.
Now, if want to sort it by last, I do:
function sort_some_people($a, $b) { return strcmp($a['last'], $b['last']); }
usort($data, 'sort_some_people');
And I have:
Array (
[0] => Array ( [name] => Mileva [last] => Einstein )
[3] => Array ( [name] => Albert [last] => Einstein )
[1] => Array ( [name] => Lieserl [last] => Einstein )
[2] => Array ( [name] => Hans Albert [last] => Einstein )
[4] => Array ( [name] => Alan [last] => Turing )
)
That is ok, now they are sorted by last. But, as you can see, I’ve just completely lost the previous sorting. What am I saying? I want to preserve array sorting as it was before, but as a secondary sorting. I hope I was clear. Practically I want to sort data using something as usort() (so, a completely custom sorting), but if sorting field is identical between two items, I want to keep their relative position as it was before. Considering the given example, I want Lieserl Einstein to appear before Mileva Einstein because it was like this at beginning.
The sorting algorithms used in PHP have this property where the order is undefined if the items match.
If you need to keep the order, then you have to roll your own code.
Fortunately some one already has:
http://www.php.net/manual/en/function.usort.php#38827
Output:
Voila!