I want to find two farthest objects (from each other) in my $user_devices array.
Every object of $user_devices has attributes: id, name, imei and coordinates. Ex.:
$user_devices = array(
'id' => '1',
'name' => 'First object',
'imei' => '123456789',
'coordinates' => '51.313032,11.798092'
);
What I'm trying to do is go through the whole array, convert latitudes and longitudes to x and y and finally calculate the distance between locations.
The problem is that this algorithm should work fast with at least 5 000 records (locations), but integrating it into a website takes about 20 seconds of load time.
How can I optimize this algorithm?
public static function get_farthest_devices($user_devices)
{
$r = 6378; // Earth radius in km
$max_distance = 0;
$count = count($user_devices);
for ($i = 0; $i < $count - 1; $i++) {
$coordinates = $user_devices[$i]->coordinates;
$coordinates_explode = explode(',', $coordinates);
$lat = $coordinates_explode[0];
$lng = $coordinates_explode[1];
$x1 = $r * cos(deg2rad($lat)) * cos(deg2rad($lng));
$y1 = $r * cos(deg2rad($lat)) * sin(deg2rad($lng));
for ($j = $i + 1; $j < $count; $j++) {
$coordinates = $user_devices[$j]->coordinates;
$coordinates_explode = explode(',', $coordinates);
$lat = $coordinates_explode[0];
$lng = $coordinates_explode[1];
$x2 = $r * cos(deg2rad($lat)) * cos(deg2rad($lng));
$y2 = $r * cos(deg2rad($lat)) * sin(deg2rad($lng));
$distance_between_points = sqrt( pow($x2-$x1, 2) + pow($y2-$y1, 2) );
if($distance_between_points > $max_distance)
{
$max_distance = $distance_between_points;
$obj_i = $user_devices[$i];
$obj_j = $user_devices[$j];
}
}
}
echo 'MAX distance is between: ' . $obj_i->name . ' (' . $obj_i->imei . ') and ' . $obj_j->name . ' (' . $obj_j->imei . ') ' . $max_distance . ' km<br/>';
}