排序数组及其索引

时间:2011-09-20 05:33:25

标签: php

  

可能重复:
  PHP sort multidimensional array by value

我有一个这样的数组 -

Array
(
    [0] => Array
        (
            [rest_id] => 1
            [restname] => Baumgart's Cafe
            [address] => 158 Franklin Avenue
            [distance] => 20.3599115829
        )

    [1] => Array
        (
            [rest_id] => 2
            [restname] => Brownstone Diner & Pancake Factory
            [address] => 426 Jersey Avenue
            [distance] => 12.422657991
        )

    [2] => Array
        (
            [rest_id] => 3
            [restname] => Jacques Torres Chocolate
            [address] => 285 Amsterdam Avenue
            [distance] => 16.3264917908
        )

    [3] => Array
        (
            [rest_id] => 4
            [restname] => Ed's Health Food
            [address] => 150 Mountain Avenue
            [distance] => 31.1066764629
        )

我想按距离排序这个数组。 任何帮助表示赞赏。 揍你。

4 个答案:

答案 0 :(得分:0)

这需要使用usort和回调来完成。

function cmp($a, $b)
{
  $ret = ($a['distance'] - $b['distance']); // this should actually be a subtraction with a comparison to a small epsilon value due to inconsistencies with floating point arithmetic

  if ($ret)
  {
    $ret = ($ret > 0 ? 1 : -1);
  }

  return $ret;
}

usort($array, 'cmp');

答案 1 :(得分:0)

usort($array, function($a,$b){
    if ($a['distance'] === $b['distance']) {
        return 0;
    }
    return ($a['distance'] < $b['distance']) ? -1 : 1;
});

答案 2 :(得分:0)

usort($array, function($a,$b){
    return (($a['distance'] == $b['distance']) ? 0 : (($a['distance'] > $b['distance']) ? 1 : -1));
});

答案 3 :(得分:0)

尽管php说它应该返回0以获得相同的答案,但只需要求助已经排序的数组并将之前的排序保留为“子排序”。事实上,这确实有效:

function cmp($a, $b) 
{
  return ($a['distance'] - $b['distance'] > 0 ? 1 : -1);
}

usort($array, 'cmp');

示例:http://codepad.viper-7.com/6RLCYM