I'll give an example, it's will be more straight to the point :
I'm working with coordinates and I want to filter the coordinates that do not belong to a set around the picked coordinate. Here for the latitude for instance :
$latitude = 4.3999291;
Basically, I have an array of latitudes, $array_latitudes
, and I want to test each one to know if they belong to a ran开发者_如何学Goge around $latitude
.
What I've done so far :
$set = range($latitude-0.2, $latitude+0.2, 0.0000001);
foreach ($array_latitudes as $lat){
if (in_array($lat, $set)){
echo $lat;
}
}
So the issue is, you guessed it, about the performance... It takes a really long time to create an array of values of a 10^-7 range !
My question, then, is : "Is there a simpler and more efficient way to return the latitudes in $array_latitudes
which belong to the set [$latitude
-0.2, $latitude
+0.2] with a precision of 10^-7 ?"
Thanks all :-)
Could you not just test
if (abs($lat - $latitude) <= 0.2) {
echo $lat;
}
?
Unless I'm misunderstanding something terribly,
if ( ($lat >= $latitude - 0.2) && ($lat <= $latitude + 0.2) )
echo $lat;
should work.
You could use array_filter
to do the reduce the array down to values that you're looking for.
class RangeFilter {
var $lowerBound = 0;
var $upperBound = 0;
function RangeFilter($lowerBound, $upperBound) {
$this->lowerBound = $lowerBound;
$this->upperBound = $upperBound;
}
function filter($value) {
return ($value <= $this->upperBound && $value >= $this->lowerBound);
}
}
$latitude = 4.3999291;
$filter = new RangeFilter($latitude - 0.2, $latitude + 0.2);
$filteredCoordinates = array_filter($coordinates, array($filter, 'filter'));
But really, if you want to be simple:
$latitude = 4.3999291;
$lowerBound = $latitude - 0.2;
$upperBound = $latitude + 0.2;
$filteredCoordinates = array();
foreach ($coordinates as $coordinate) {
if ($coordinate <= $upperBound && $coordinate >= $lowerBound) {
$filteredCoordinates[] = $coordinate;
}
}
精彩评论