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?

0

4 Answers 4

3

You can use usort and compare the distance in your comparison function:

usort($arr, function($a, $b){
    return $a['distance'] - $b['distance'];
});
Sign up to request clarification or add additional context in comments.

Comments

2

Edit:

I think I understand what it is you want to achieve now. Try this:

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');

5 Comments

Thanks for the answer - I have used the usual sort functions and they don't work.
@30secondstosam Could you try my new solution?
Worked a TREAT! great bit of code. I'll certainly re use that. thank you!! @silkfire
@30secondstosam You're welcome. I use this custom function all the time.
it's brilliant. Unfortunately StackOverflow has become a popularity contest, but this should be the answer that gets the votes.
0

An alternative that I've found to organize my arrays is putting them as key, and then organizing with these keys.

Example (using your code):

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

ksort($arr);

Comments

0

You can use the usort for sorting an array on personalized rules

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

    usort($array, "sortOnDistance");
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.