I have a multidimensional array and want to sort it by distance:
[clustermarkers] => [
0 => [
0 => [
'name' => 'A',
'distance' => 10
]
],
1 => [
0 => [
'name' => 'B',
'distance' => 8
]
],
...
];
I have tried usort function, but something wrong:
usort($clustermarkers, function($a, $b) {
return (int)$a['distance'] - (int)$b['distance'];
});
In your usort
function, just add [0]
to $a
and $b
before ['distance']
usort($clustermarkers, function ($a, $b) {
return $a[0]['distance'] - $b[0]['distance'];
});
print_r($clustermarkers);
Almost:
usort($clustermarkers, function($a, $b) {
return $a['distance'] > $b['distance']; //Distance ASC
});
usort($clustermarkers, function($a, $b) {
return $a['distance'] < $b['distance']; //Distance DESC
});
note the <
and >
operators and not casting to int