Files
liche/common/helpers/search_helper.php
2021-07-05 09:56:27 +08:00

103 lines
2.9 KiB
PHP
Executable File

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if(! function_exists('get_distance'))
{
function get_distance($lat1, $lng1, $lat2, $lng2)
{
$earth_radius = 6371.393;//地球平均半径
$pi = 3.1415926535898;
$radLat1 = $lat1 * $pi / 180.0;
$radLat2 = $lat2 * $pi / 180.0;
$a = $radLat1 - $radLat2;
$b = ($lng1 * $pi / 180.0) - ($lng2 * $pi / 180.0);
$s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
$s = $s * $earth_radius;
$s = round($s * 1000);
return $s;
}
}
if(! function_exists('get_geo_dist'))
{
function get_geo_dist($geodist)
{
$geodist = intval($geodist ? $geodist : 0);
return $geodist > 1000 ? sprintf("%.1f",($geodist/1000)).'km' : $geodist.'m';
}
}
/**
* @param string $idx
* @param string $keyword
* @param int $page
* @param array $filter {"k":[]} or {"k":{"v":[], "exc":"bool 1不包含,0包含"}}
* @param array $order
* @param array $geo
* @param int $page_size
* @param array $range
* @return mixed
*/
if(! function_exists('search_by_sphinx'))
{
function search_by_sphinx($idx, $keyword = '', $page = 1, $filter = array(), $order = array(), $geo = array(), $page_size = 10, $range = array() ,$groupby=array())
{
$CI = & get_instance();
$CI->config->load('sphinx', true, true);
$config = $CI->config->item('sphinx');
require_once COMMPATH.'third_party/Sphinxclient.php';
$sphinxclient = new Sphinxclient();
$sphinxclient->SetServer($config['host'], $config['port']);
if($filter)
{
foreach($filter as $k => $v)
{
if($v['v']){
$sphinxclient->SetFilter($k, $v['v'], boolval($v['exc']));
} else {
$sphinxclient->SetFilter($k, $v);
}
}
}
if($range)
{
foreach($range as $k => $v)
{
$sphinxclient->SetFilterRange($k, $v[0], $v[1]);
}
}
if($geo)
{
$sphinxclient->SetGeoAnchor('lat', 'lng', (float) deg2rad($geo['lat']), (float) deg2rad($geo['lng'])); //角度转换成弧度
}
if($groupby){
$sphinxclient->SetGroupBy ( $groupby[0], SPH_GROUPBY_ATTR,$groupby[1]);
}
if($order)
{
$sphinxclient->SetSortMode($order[0], $order[1]);
}
$sphinxclient->setLimits(intval(($page - 1) * $page_size), intval($page_size), $config['SPHINX_MAX_MATCHES']);
if($result = $sphinxclient->query($keyword, $idx))
{
return $result;
}
debug_log($sphinxclient->GetLastError(), 'sphinx.log');
return false;
}
}