0

Below are the results of my array $geocodedList:

array (size = 6) 
   0 => 
     object (Geocoder \ Result \ Geocoded) [24] 
       protected 'latitude' => float -22.4363597 
       protected 'longitude' => float -46.8106841 
       public 'distance' => float 1500 
   1 => 
     object (Geocoder \ Result \ Geocoded) [14] 
       protected 'latitude' => float -22.4349613 
       protected 'longitude' => float -46.8275498 
       public 'distance' => float 1740 
   2 => 
     object (Geocoder \ Result \ Geocoded) [25] 
       public 'distance' => float 152 

It is an array with several objects (Geocoded) inside. I want to organize this array by 'distance' attribute of these objects. I want the result to be:

0 => public 'distance' => 152 (item 2 of old array)
1 => public 'distance' => 1500 (item 0 of old array)
2 => public 'distance' => 1740 (item 1 of old array)

How to proceed? I tried several things but could not get anything.

dynamic
  • 46,985
  • 55
  • 154
  • 231

1 Answers1

0

You can use usort() to specify a custom comparison method:

function cmp($a, $b) {
    if ($a->distance == $b->distance) {
        return 0;
    }
    return ($a->distance < $b->distance) ? -1 : 1;
}

usort($array, "cmp");

Or equivalent with anonymous function:

usort($array, function ($a, $b) {
    if ($a->distance == $b->distance) {
        return 0;
    }
    return ($a->distance < $b->distance) ? -1 : 1;
});
dynamic
  • 46,985
  • 55
  • 154
  • 231