So, I have an array of objects that I want to sort like so:
Array
(
[463] => stdClass Object
(
[name] => Organic 12
[total_weight] => 5
)
[340] => stdClass Object
(
[name] => Organic 12b
[total_weight] => 5
)
[340] => stdClass Object
(
[name] => Organic 12c
[total_weight] => 5
)
[532] => stdClass Object
(
[name] => Alpha 10
[total_weight] => 4
)
[203] => stdClass Object
(
[name] => General 5
[total_weight] => 3
)
)
Where the total_weight of all objects is sorted highest to lowest, then within those sorts, the objects are sorted alphabetically by name. I successfully can sort them by total_weight with php’s usort, but can’t figure out how to sub-sort the result. Using usort only, there’s no consistency in the sorted results so one object’s name might appear above another’s in one result, but not in another.
I’m thinking perhaps array_multisort might be the answer, but I can’t seem to figure it out.
Write your own comparing function and apply it by usort. The trick is to apply additional comparison when weights are equal.
Should look like this: