按照距离对内容进行排序

I am developing an application with the Geotools package and I have one problem:

public function prodcercanos()
{
    $cercanos = User::with('municipio')->with('productos')->get();
    $coordA   = Geotools::coordinate([44.4578589, 2.2951061999999998]); 
    foreach ($cercanos as $p) {
        $coordB   = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
        $distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
        echo $p->id;
        echo "<p>";
        echo $distance->in('km')->haversine();
        echo "</p>";
    }       
}

This code returns the distance between points in the foreach but I need to sort the foreach with the distance and I don't know how could I make this.

Anyone could help me?

In the foreach loop, put it all in an array, and than go over the array. You can use the distance as the key, and the HTML output as a value. You can use ksort function on the array to sort it by key.

public function prodcercanos()
    {
        $cercanos = User::with('municipio')->with('productos')->get();
        $coordA   = Geotools::coordinate([44.4578589, 2.2951061999999998]); 
        $output = [];
        foreach ($cercanos as $p) {
            $coordB   = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
            $distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
            $dis = $distance->in('km')->haversine();
            $output[$dis] = $p->id . "<p>$dis</p>";
        }       
        ksort($output);
        foreach ($output as $line) {
            echo $line;
        }
    }

Use the sort() function in PHP. Syntax to use: sort(array,sortingtype);

Use the following link for more information: http://www.w3schools.com/php/func_array_sort.asp