我需要按距离对此数组进行排序
Array
(
[0] => Array
(
[name] => Pyro Pizza
[distance] => 2.3
)
[1] => Array
(
[name] => Sparky's Pizza
[distance] => 2.1
)
[2] => Array
(
[name] => American Dream Pizza - Portland
[distance] => 0.5
)
[3] => Array
(
[name] => Ken's Artisan Pizza
[distance] => 1.1
)
[4] => Array
(
[name] => Sparky's Pizza - SE
[distance] => 2.2
)
[5] => Array
(
[name] => Vincente's Gourmet Pizza and the V-Room
[distance] => 2
)
[6] => Array
(
[name] => Blind Onion Pizza and Pub
[distance] => 0.6
)
[7] => Array
(
[name] => Hot Lips Pizza
[distance] => 1.9
)
[8] => Array
(
[name] => Flying Pie Pizzeria
[distance] => 2
)
[9] => Array
(
[name] => Hammy's Pizza
[distance] => 2.4
)
)
我用过这个..
usort($results, 'sortByOrder');
用这个..
function sortByOrder($a, $b) {
return $a['distance'] - $b['distance'];
}
但它不起作用
答案 0 :(得分:3)
答案 1 :(得分:3)
这应该做的工作:
function sortByOrder($a, $b) {
if ( $a ['distance'] == $b ['distance'] ) return 0;
return ( $a ['distance'] < $b ['distance'] ) ? -1 : 1;
}
usort ( $results, 'sortByOrder' );
你的代码的问题是比较函数sortByOrder在这里应该返回0如果它们相等,或者如果其中一个更大则返回-1/1。但是你的函数返回了距离的差异,这是usort()无法解析的。
答案 2 :(得分:2)
function sortByOrder($a, $b) {
if ($a['distance'] == $b['distance']) return 0;
return ($a['distance'] < $b['distance']) ? -1 : 1;
}