I need help sorting an associative array with PHP.
The sorting should rely on the array key "name", and keep the key/value pairs. Following sorting order: 1) first integer ASC, 2) second integer ASC, 3) third mixed ASC
input
array(6) {
[0]=>
array(2) {
["name"]=>
string(13) "60 to 90 in 6"
["timing"]=>
float(4.7)
}
[1]=>
array(2) {
["name"]=>
string(15) "40 to 120 in KD"
["timing"]=>
float(3.3)
}
[2]=>
array(2) {
["name"]=>
string(14) "60 to 100 in 4"
["timing"]=>
float(1.5)
}
[3]=>
array(2) {
["name"]=>
string(13) "60 to 90 in 4"
["timing"]=>
float(2.4)
}
[4]=>
array(2) {
["name"]=>
string(15) "140 to 160 in 6"
["timing"]=>
float(2.4)
}
[5]=>
array(2) {
["name"]=>
string(13) "60 to 90 in KD"
["timing"]=>
float(5.7)
}
}
output order
1, 3, 0, 5, 2, 4
Thank you very much for your help.
Answer:
uasort($acceleration, function($a, $b) {
if($a['_sort'][0] == $b['_sort'][0] AND $a['_sort'][2] == $b['_sort'][2])
{
if($a['_sort'][4] < $b['_sort'][4])
return -1;
elseif($a['_sort'][4] > $b['_sort'][4])
return 1;
else
return 0;
}
elseif($a['_sort'][0] == $b['_sort'][0])
{
if($a['_sort'][2] < $b['_sort'][2])
return -1;
elseif($a['_sort'][2] > $b['_sort'][2])
return 1;
return 0;
}
else
{
if($a['_sort'][0] < $b['_sort'][0])
return -1;
elseif($a['_sort'][0] > $b['_sort'][0])
return 1;
else
return 0;
}
});
I'm sure, there is a more elegant way, but may serve as input.