优化php - 获取特定半径的所有帖子

时间:2017-09-05 23:51:10

标签: php mysql sql arrays json

所以我首先制作了一个边框,然后在该框中进行协调。问题是查询仍需要3秒钟才能完成(表中有20,000个条目)。我有latitudelongitudedeleted作为索引。我无法弄清楚还有哪些可以优化。我知道我还没有实施过PDO,但那是一个不同的故事。

我认为json_encode功能花了太长时间:

<?php
include 'connection.php';
error_reporting(0);

if($_GET["lat"]){
    $radius = $_GET["radius"];
    $maxLat = $_GET["lat"] + rad2deg($radius/3959);
    $minLat = $_GET["lat"] - rad2deg($radius/3959);
    $maxLon = $_GET["long"] + rad2deg(asin($radius/3959) / cos(deg2rad($_GET["lat"])));
    $minLon = $_GET["long"] - rad2deg(asin($radius/3959) / cos(deg2rad($_GET["lat"])));

    //Query to get events within specified distance
    $qry = @"SELECT `Posts`,`Votes`,`Date`,`Latitude`,`Longitude`,`PostID`,`Comments`, 
            `Picture`, `City`, `DeviceID`, (((acos(sin((".$_GET["lat"]."*pi()/180)) * 
            sin((`latitude`*pi()/180))+cos((".$_GET["lat"]."*pi()/180)) * 
            cos((`latitude`*pi()/180)) * cos(((".$_GET["long"]."- `longitude`)*pi()
            /180))))*180/pi())*60*1.1515) as distance FROM `TABLE` WHERE `deleted`= 0 AND 
            `latitude` Between $minLat AND $maxLat AND `longitude` Between $minLon AND 
            $maxLon HAVING distance <= $radius ORDER BY `PostID` DESC LIMIT 60 " ;
    $result = mysql_query($qry);

    if (!$result) {
        die("Query to show fields from table failed");
    }

    $json = array();

    $json[] = array('Posts' => $row[0], 
                    'Votes' => $row[1], 
                    'Date' => $row[2], 
                    'Latitude' => $row[3], 
                    'Longitude' => $row[4], 
                    'PostID' => $row[5], 
                    'comments' => $row[6], 
                    'canvote' => $id, 
                    'picture' => $row[7], 
                    'city' => $row[8], 
                    'DeviceID' => $row[9]);

    echo json_encode($json);
else {
    echo 'Error';
}
?>

0 个答案:

没有答案