Search code examples
phppostal-codearray-multisort

PHP - array_multisort ? Sorting postal code (zip code)


After calculating distances between two points using latitude and longitude, I've created an array which looks like this:

$enterprises = array();

//Ex.: Array ( [0] => Array ( [A0A0A0] => 0 ) [1] => Array ( [A0A1A0] => 22.794344863539 ) 
for ($i=0; $i < count($cpEnterprise) ; $i++) {

        $enterprises[] = array($cpEnterprise[$i] => distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k'));

}

The main array contains the enterprises that is needed for a comparison with the actual postal codes inside it. POSTAL CODE => DISTANCE.

I need to sort those inner arrays by distance from the nearest to the farthest and I don't really understand how array_multisort works...


Solution

  • An easy way to tackle this is to restructure your array and use asort

    $enterprises = array();
    
    //Ex.: Array ( [0] => Array ( [A0A0A0] => 0 ) [1] => Array ( [A0A1A0] => 22.794344863539 ) 
    for ($i=0; $i < count($cpEnterprise) ; $i++) {    
            $enterprises[$cpEnterprise[$i]] = distance($actualCpLat, $actualCpLong, $businessLat[$i], $businessLong[$i], 'k');
    
    }
    asort($enterprises);