doucheng2210 2014-12-06 16:46
浏览 113

按循环中的函数对foreach进行排序

I am making my first ever PHP app and I am flummoxed at the final hurdle.

I am looping my results and need to sort the results of a function inside a foreach loop in PHP.

If anyone has any insight into how I can do this it is much appreciated!

foreach($data as $d) {
echo $d["StudioName"]; // This will output "This is a test!"

echo distance($lat, $lng, $d['StudioLat'], $d['StudioLong']);}

Basically I need is to be sorted by the "distance" function results.

$sqlSelect = "SELECT * FROM studios WHERE StudioLat BETWEEN $minlat AND $maxlat AND StudioLong BETWEEN $minlng AND $maxlng"; // Basic SQL SELECT Statment

$data = $dataBase->getQuery($sqlSelect); // This will run the SQL statment and return and associative array.
  • 写回答

1条回答 默认 最新

  • donglu9872 2014-12-06 16:53
    关注

    Sort the array using usort and a callback:

    usort($data, function($a, $b) use ($lat, $lng) {
      $da = distance($lat, $lng, $a['StudioLat'], $a['StudioLong']);
      $db = distance($lat, $lng, $b['StudioLat'], $b['StudioLong']);
      return $da - $db;
    });
    

    After that, you can loop through the array and output its items, just like you did.

    评论

报告相同问题?