On Fri, Jul 16, 2010 at 2:48 PM, Hans Zaunere <li...@zaunere.com> wrote:
> Closures - great for Javascript, but for PHP?  In a non-callback-centric
> synchronous language such as PHP, what else can we use this "syntactic
> sugar" for?  How are people using them and what can we gain from them?  And,
> the hell with code reuse?

I have a favorite problem, that is hard/ugly to solve without closures:

Given an array of businesses with latitude/longitude coordinates, and
the user's location, sort the array of businesses by closest to the
user.

so you have:

$stores = array(
  array('name' => 'Pet Smart', 'lat'=>24.12, 'lon' => 54.23),
  array('name' => 'Cats and Critter', 'lat'=>24.19, 'lon' => 54.32),
  array('name' => 'Snakes and such', 'lat'=>24.45, 'lon' => 53.35),
  array('name' => 'Lots of llams', 'lat'=>24.46, 'lon' => 54.97));

$user_location = array('lat'=> 24.45, 'lon' => 54.96);

// Solution using closures

// geo sort.
function sort_by_closest(&$points,$location) {
  usort($points, function($a,$b) use($location) {
    return distance($a,$location) > distance($b,$location);
  });
}

// geo distance using sperical law of cosines.
function distance($a,$b) {
        $R = 6371; // km
        $d2r = pi() / 180;
        return acos(sin($a['lat']*$d2r)*sin($b['lat']*$d2r) +
                          cos($a['lat']*$d2r)*cos($b['lat']*$d2r) *
                          cos($b['lon']*$d2r-$a['lon']*$d2r)) * $R;
}

print_r($stores);
sort_by_closest($stores,$user_location);
print_r($stores);


-John
_______________________________________________
New York PHP Users Group Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk

http://www.nyphp.org/Show-Participation

Reply via email to