1

I have an array that contains a number of arrays. Like this:

array{
    array{
        id => 1
        name => place_1
        lat => 56.1705
        lon => 10.2010
        distance => 1.545
    }
    array{
        id => 14
        name => place_14
        lat => 56.1715
        lon => 10.2049
        distance => 1.765
    }
    //etc etc
}

I need to sort the arrays within the array by distance, from low to high - or at least get the position of the lowest distance in the array (like $array[1][4] == 1.765).

I have done something similar before. Then I did it with a function like this:

function sort_by_dist($a, $b){
    return $a['distance'] - $b['distance'];
}
usort($array, 'sort_by_dist');

However, this will in this case only return bool(true) I have no idea why it acts this way.

I know this question has probably been asked (and answered) before, but as a non-native speaker of English I am a bit at a loss as to what I should search for.

Thank you for your help!

1
  • By definition, usort will return a boolean as per: php.net/manual/en/function.usort.php the array $array will be sorted according to the function you defined (sort_by_dist) Commented Nov 27, 2014 at 23:11

2 Answers 2

2

My answer just reformats your function a little to make it more explicit what is going on:

$a = array(
    array(
        'id' => 14,
        'name' => 'place_14',
        'lat' => 56.1715,
        'lon' => 10.2049,
        'distance' => 1.765,
    ),
    array(
        'id' => 1,
        'name' => 'place_1',
        'lat' => 56.1705,
        'lon' => 10.2010,
        'distance' => 1.545,
    ),
);

usort($a, function($a, $b) {
    $d1 = $a['distance'];
    $d2 = $b['distance'];

    if ($d1 == $d2) {
        return 0;
    }
    return ($d1 < $d2) ? -1 : 1;
});

// the array $a is sorted.
print_r($a);

The input array to usort is sorted, usort will return false if the sorting failed and true otherwise.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_multisort by iterating thought the array like so:

function sort_by(&$array, $subkey ) {
    foreach ($array as $subarray) {
        $keys[] = $subarray[$subkey];
    }
    array_multisort($keys, SORT_ASC, $array);
}
sort_by($coords, 'distance');// $coords is now sorted by distance

$coords is your multidimensional array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.