<?php

function mp_coord_already_exist(&$coordinates, &$locations) {
	foreach ($locations as $location) {
		if ($location->coordinates->lat == $coordinates->lat)
			if ($location->coordinates->lng == $coordinates->lng)
				return $location;
	}
	return null;
}

function mp_sort_n_insert(&$event, &$locations) {
	$coordinates = $event->location->coordinates;

	$already_exist = mp_coord_already_exist($coordinates, $locations);
	if ($already_exist) {
		// add event to events[]
		array_push($already_exist->events, $event);
	}
	else {
		// create new location object
		$location = (object)[];
		$location->events = [];

		// add coordinates to the location
		$location->coordinates = $coordinates;
		// add first event to events[]
		array_push($location->events, $event);
		// add this location to locations[]
		array_push($locations, $location);
	}
}

function mp_sort_events($events) {
	$locations = [];
	
	foreach ($events as $event) {
		mp_sort_n_insert($event, $locations);
	};

	return $locations;
}

?>
