Jump to content

Sort Array Question


Tom.
 Share

Recommended Posts

Sorry, this is a little bit of an easy question. But I was just wondering why this wasn't working: 

So I have a map field that will have a longitude and latitude. I'm using this to calculate the distance between each entry and storing this in the PageArray. 

function distance($point1, $point2) {
	$radius = 3958;   
	$degPerRad = 57.29578;
	
	$distance = ($radius * pi() * sqrt(
		    ($point1->lat - $point2->lat)
		    * ($point1->lat - $point2->lat)
		    + cos($point1->lat / $degPerRad)  
		    * cos($point2->lat / $degPerRad)  
		    * ($point1->lng - $point2->lng)
		    * ($point1->lng - $point2->lng)
		    ) / 180);
	
	return round($distance);
}

function get_distance($start, $results, $radius = 30) {
	foreach($results as $result) {
		$result->distance = distance($start->map, $result->map);
		if($result->distance > $radius) { $results->remove($result); }
	}
	
	usort($results, function($a, $b){
		if($a->distance == $b->distance) { return 0; }
		return $a->distance > $b->distance ? 1 : -1;
	});
	
	return $results;
}

For some reason the usort will not work. However I managed to figure it out by using:

$filter = $results->getArray();
usort($filter, function($a, $b){
	if($a->distance == $b->distance) { return 0; }
	return $a->distance > $b->distance ? 1 : -1;
});
$results->setArray($filter);

Though it will duplicate the last returned item. Here is how I'm accessing the function:

$activities = $pages->find("template=activity, id!=$page");
$nearby = get_distance($page, $activities, 40);
Link to comment
Share on other sites

I didn't manage to figure out the reason behind the duplication. However as always ProcessWire saves the day. I thought the sort function only worked with fields set in the database. However I thought I'd just try it:

$results->sort("distance");

works perfectly. Ryan you're a God. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...