Okay, this one is pretty complicated… lets say I have an array called $data
Array
(
[9e5b0d6d-711c-4cd0-8697-634a5c640066] => Array
(
[player] => 9e5b0d6d-711c-4cd0-8697-634a5c640066
[wins] => 1
[loss] => 6
[winsR] => 2
[lossR] => 12
)
[a8f7fb4c-afab-4ec0-9202-b87fa2641110] => Array
(
[player] => a8f7fb4c-afab-4ec0-9202-b87fa2641110
[wins] => 1
[loss] => 6
[winsR] => 2
[lossR] => 12
)
[96ed2f95-08bd-42f8-bb57-9df09b66109d] => Array
(
[player] => 96ed2f95-08bd-42f8-bb57-9df09b66109d
[wins] => 2
[loss] => 5
[winsR] => 4
[lossR] => 10
)
[2a4e1a3e-cde4-4c9b-947e-67a4d333f0f4] => Array
(
[player] => 2a4e1a3e-cde4-4c9b-947e-67a4d333f0f4
[wins] => 3
[loss] => 4
[winsR] => 6
[lossR] => 8
)
[08c23d63-69a9-4147-b40f-64b241cfbb4f] => Array
(
[player] => 08c23d63-69a9-4147-b40f-64b241cfbb4f
[wins] => 4
[loss] => 3
[winsR] => 8
[lossR] => 6
)
[777e8f3e-caac-41fb-975e-a410e42f7114] => Array
(
[player] => 777e8f3e-caac-41fb-975e-a410e42f7114
[wins] => 5
[loss] => 2
[winsR] => 11
[lossR] => 4
)
[9cd5256f-6d3a-4bd5-aeed-b6904bcbf048] => Array
(
[player] => 9cd5256f-6d3a-4bd5-aeed-b6904bcbf048
[wins] => 6
[loss] => 1
[winsR] => 12
[lossR] => 3
)
[797c95df-c334-4328-a8eb-4ba5e690af4d] => Array
(
[player] => 797c95df-c334-4328-a8eb-4ba5e690af4d
[wins] => 6
[loss] => 1
[winsR] => 12
[lossR] => 2
)
)
As you can see, I have a series of data, and each element has it’s own nested array. I already know I can sort the array using a single nested value using
usort($data, create_function('$a, $b', 'return $b["wins"] - $a["wins"];'));
However, this is not enough.
The problem is, sorting with the above function doesn’t sort deep enough for me. All it does is sort based on the following:
- [‘wins’] DESCENDING (highest wins sorted first)
I would like to sort using FOUR nested values.
- [‘wins’] DESCENDING (highest wins sorted first)
- [‘loss’] ASCENDING (lowest loss sorted second)
- [‘winsR’] DESCENDING (highest winsR sorted third)
- [‘lossR’] ASCENDING (lowest lossR sorted fourth)
I know this is pretty complicated, so I’m coming here to ask for help. What would be the best and most efficient way to do this?
What you’re looking for is the function
usort().There, you can supply your own comparator that can compare two elements and apply the rules you wish to use.
You were on the right track, but your comparator function can be much more elaborate: