按距离多排序
Multisort by distance
我有一个多维数组,想按距离对它进行排序:
[clustermarkers] => [
0 => [
0 => [
'name' => 'A',
'distance' => 10
]
],
1 => [
0 => [
'name' => 'B',
'distance' => 8
]
],
...
];
我试过 usort 函数,但有些地方不对:
usort($clustermarkers, function($a, $b) {
return (int)$a['distance'] - (int)$b['distance'];
});
差不多:
usort($clustermarkers, function($a, $b) {
return $a['distance'] > $b['distance']; //Distance ASC
});
usort($clustermarkers, function($a, $b) {
return $a['distance'] < $b['distance']; //Distance DESC
});
注意 <
和 >
运算符,而不是转换为 int
在您的 usort
函数中,只需将 [0]
添加到 $a
和 $b
之前 ['distance']
usort($clustermarkers, function ($a, $b) {
return $a[0]['distance'] - $b[0]['distance'];
});
print_r($clustermarkers);
我有一个多维数组,想按距离对它进行排序:
[clustermarkers] => [
0 => [
0 => [
'name' => 'A',
'distance' => 10
]
],
1 => [
0 => [
'name' => 'B',
'distance' => 8
]
],
...
];
我试过 usort 函数,但有些地方不对:
usort($clustermarkers, function($a, $b) {
return (int)$a['distance'] - (int)$b['distance'];
});
差不多:
usort($clustermarkers, function($a, $b) {
return $a['distance'] > $b['distance']; //Distance ASC
});
usort($clustermarkers, function($a, $b) {
return $a['distance'] < $b['distance']; //Distance DESC
});
注意 <
和 >
运算符,而不是转换为 int
在您的 usort
函数中,只需将 [0]
添加到 $a
和 $b
之前 ['distance']
usort($clustermarkers, function ($a, $b) {
return $a[0]['distance'] - $b[0]['distance'];
});
print_r($clustermarkers);