1

I have an array that loops through a set of a values, this is how it looks:

$arr[] = array("name" => $name, 
               "add1" => $add1, 
               "add2" => $add2, 
               "add3" => $add3, 
             "postcode" => $pc, 
       "distance" => $distance);

Simple and quick question (although I'm struggling with the answer), I was wondering how I can sort the array into distance ascending (which is a floating number) order?

4

4 回答 4

3

您可以使用usort并在比较函数中比较距离:

usort($arr, function($a, $b){
    return $a['distance'] - $b['distance'];
});
于 2013-07-05T14:01:28.363 回答
2

编辑

我想我明白你现在想要实现什么。尝试这个:

function array_sort_by_column(&$array, $col, $direction = SORT_ASC) {
    $sort_col = array();

    foreach ($array as $key => $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $direction, $array);
}

array_sort_by_column($arr, 'distance');
于 2013-07-05T13:58:45.143 回答
0

我发现组织数组的另一种方法是将它们作为键,然后使用这些键进行组织。

示例(使用您的代码):

$arr = array();    
$arr[$distance] = array("name" => $name, 
                   "add1" => $add1, 
                   "add2" => $add2, 
                   "add3" => $add3, 
                 "postcode" => $pc, 
           "distance" => $distance);

ksort($arr);
于 2013-07-05T14:03:08.360 回答
0

您可以使用 usort 根据个性化规则对数组进行排序

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

    usort($array, "sortOnDistance");
?>
于 2013-07-05T14:06:43.160 回答