温馨提示:本文共22807个字,读完预计58分钟。
/* 对象转数组 */
function object_to_array($obj) {
$obj = (array)$obj;
foreach ($obj as $k => $v) {
if (gettype($v) == 'resource') {
return;
}
if (gettype($v) == 'object' || gettype($v) == 'array') {
$obj[$k] = (array)object_to_array($v);
}
}
return $obj;
}
//数组转对象 function array_object($array) { if (gettype($array) != 'array') { return; } foreach ($array as $k => $v) { if (gettype($v) == 'array' || getType($v) == 'object') { $array[$k] = (object)$this->array_object($v); } } return (object)$array; }
/* 文字替换*/
function m_s($a){
$url=$_SERVER[‘HTTP_HOST’];
if($url=='zbsc.yunbaozb.com'){
$l=strlen($a);
$sl=$l-6;
$s='';
for($i=0;$i<$sl;$i++){
$s.='*';
}
$rs=substr_replace($a,$s,3,$sl);
return $rs;
}
return $a;
}
/**
* 格式化输出
*/
function dump($var, $echo = true, $label = null, $strict = true)
{
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
} else
return $output;
}
/**
* 版本号比较,位数一定要相等,例2.13.5和2.13.4或1.24.5.2和2.2.2.2
* @param $base_version
* 基准版本号
* @param $version
* 比对版本号
* @return bool -1小,0相等,1大
*/
function versionBool($base_version, $version)
{
$base_version = explode('.', $base_version);
$version = explode('.', $version);
$count = count($base_version);
for ($i = 0; $i < $count; $i++) {
if ($base_version[$i] < $version[$i]) {
return 1;
} elseif ($base_version[$i] == $version[$i] && $i >= $count – 1) {//相等的情况,需要三个版本位都相等
return 0;
} elseif ($base_version[$i] > $version[$i]) {
return -1;
}
}
return true;
}
/* 时长格式化 */
function secondsFormat($time)
{
$now = time();
$cha = $now – $time;
if ($cha < 60) {
return '刚刚';
}
if ($cha >= 4 * 24 * 60 * 60) { //超过4天
$now_year = date('Y', $now);
$time_year = date('Y', $time);
if ($now_year == $time_year) {
return date("m月d日", $time);
} else {
return date("Y年m月d日", $time);
}
} else {
$iz = floor($cha / 60);
$hz = floor($iz / 60);
$dz = floor($hz / 24);
if ($dz > 3) {
return '3天前';
} else if ($dz > 2) {
return '2天前';
} else if ($dz > 1) {
return '1天前';
}
if ($hz > 1) {
return $hz . '小时前';
}
return $iz . '分钟前';
}
}
///////////////////////////////////////快递鸟物流信息查询start/////////////////////////////////////////////
//获取物流状态【即时查询版】
function getExpressStateInfo($express_code, $express_number, $express_name, $username)
{
$express_info = [];
$express_info_kdn = getExpressInfoByKDN($express_code, $express_number);
$express_state = $express_info_kdn[‘State’]; //物流状态 0-暂无轨迹信息 1-已揽收 2-在途中 3-已签收4-问题件
if (!$express_state) {
$express_info[‘state_name’] = '包裹正在等待揽收';
$express_info[‘desc’] = $express_name . ' ' . $express_number;
} elseif ($express_state == 1) {
$express_info[‘state_name’] = '包裹已揽收';
$express_info[‘desc’] = $express_name . ' ' . $express_number;
} elseif ($express_state == 2) {
$express_info[‘state_name’] = '包裹运输中';
$express_info[‘desc’] = $express_name . ' ' . $express_number;
} elseif ($express_state == 3) {
$express_info[‘state_name’] = '包裹已签收';
$express_info[‘desc’] = '签收人:' . $username;
}
return $express_info;
}
//快递鸟获取物流信息
function getExpressInfoByKDN($express_code,$express_number){
$configpri=getConfigPri();
$express_type=isset($configpri[‘express_type’])?$configpri[‘express_type’]:'';
$EBusinessID=isset($configpri[‘express_id_dev’])?$configpri[‘express_id_dev’]:'';
$AppKey=isset($configpri[‘express_appkey_dev’])?$configpri[‘express_appkey_dev’]:'';
//$ReqURL='http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json'; //免费版即时查询【快递鸟测试账号专属查询地址】
$ReqURL='http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx'; //免费版即时查询【已注册商户ID真实即时查询地址】
if($express_type){ //正式付费物流跟踪版
$EBusinessID=isset($configpri[‘express_id’])?$configpri[‘express_id’]:'';
$AppKey=isset($configpri[‘express_appkey’])?$configpri[‘express_appkey’]:'';
$ReqURL='http://api.kdniao.com/api/dist'; //物流跟踪版查询【已注册商户ID真实即时查询地址】
}
$requestData=array(
'ShipperCode'=>$express_code,
'LogisticCode'=>$express_number
);
$requestData= json_encode($requestData);
$datas = array(
'EBusinessID' => $EBusinessID,
'RequestType' => '1002',
'RequestData' => urlencode($requestData) ,
'DataType' => '2',
);
//物流跟踪版消息报文
if($express_type){
$datas[‘RequestType’]='1008';
}
$datas[‘DataSign’] = encrypt_kdn($requestData, $AppKey);
$result=sendPost_KDN($ReqURL, $datas);
return json_decode($result,true);
}
/**
* 快递鸟电商Sign签名生成
* @param data 内容
* @param appkey Appkey
* @return DataSign签名
*/
function encrypt_kdn($data, $appkey) {
return urlencode(base64_encode(md5($data.$appkey)));
}
/**
* post提交数据
* @param string $url 请求Url
* @param array $datas 提交的数据
* @return url响应返回的html
*/
function sendPost_KDN($url, $datas) {
$temps = array();
foreach ($datas as $key => $value) {
$temps[] = sprintf('%s=%s', $key, $value);
}
$post_data = implode('&', $temps);
$url_info = parse_url($url);
if(empty($url_info[‘port’]))
{
$url_info[‘port’]=80;
}
$httpheader = "POST " . $url_info[‘path’] . " HTTP/1.0\r\n";
$httpheader.= "Host:" . $url_info[‘host’] . "\r\n";
$httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
$httpheader.= "Connection:close\r\n\r\n";
$httpheader.= $post_data;
$fd = fsockopen($url_info[‘host’], $url_info[‘port’]);
fwrite($fd, $httpheader);
$gets = "";
$headerFlag = true;
while (!feof($fd)) {
if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
while (!feof($fd)) {
$gets.= fread($fd, 128);
}
fclose($fd);
return $gets;
}
function is_true($val, $return_null=false){
$boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
return ( $boolval===null && !$return_null ? false : $boolval );
}
///////////////////////////////////////快递鸟物流信息查询end/////////////////////////////////////////////
/**
* 判断是否为合法的身份证号码
* @param $mobile
* @return int
*/
function isCreditNo($vStr)
{
return true;
$vCity = array(
'11', '12', '13', '14', '15', '21', '22',
'23', '31', '32', '33', '34', '35', '36',
'37', '41', '42', '43', '44', '45', '46',
'50', '51', '52', '53', '54', '61', '62',
'63', '64', '65', '71', '81', '82', '91'
);
if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) {
return false;
}
if (!in_array(substr($vStr, 0, 2), $vCity)) {
return false;
}
$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
$vLength = strlen($vStr);
if ($vLength == 18) {
$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
} else {
$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
}
if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
return false;
}
if ($vLength == 18) {
$vSum = 0;
for ($i = 17; $i >= 0; $i–) {
$vSubStr = substr($vStr, 17 – $i, 1);
$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
}
if ($vSum % 11 != 1) {
return false;
}
}
return true;
}
/* 时长格式化 */
function getBanSeconds($cha, $type = 0)
{
$iz = floor($cha / 60);
$hz = floor($iz / 60);
$dz = floor($hz / 24);
/* 秒 */
$s = $cha % 60;
/* 分 */
$i = floor($iz % 60);
/* 时 */
$h = floor($hz / 24);
/* 天 */
if ($type == 1) {
if ($s < 10) {
$s = '0' . $s;
}
if ($i < 10) {
$i = '0' . $i;
}
if ($h < 10) {
$h = '0' . $h;
}
if ($hz < 10) {
$hz = '0' . $hz;
}
return $hz . ':' . $i . ':' . $s;
}
if ($cha < 60) {
return $cha . '秒';
} else if ($iz < 60) {
return $iz . '分钟' . $s . '秒';
} else if ($hz < 24) {
return $hz . '小时' . $i . '分钟';
} else if ($dz < 30) {
return $dz . '天' . $h . '小时';
}
}
/* 生成二维码 */
function scerweima($url = '')
{
$key = md5($url);
//生成二维码图片
$filename2 = '/upload/qr/' . $key . '.png';
$filename = API_ROOT . '/../public/upload/qr/' . $key . '.png';
if (!file_exists($filename)) {
require_once API_ROOT . '/../sdk/phpqrcode/phpqrcode.php';
$value = $url; //二维码内容
$errorCorrectionLevel = 'H'; //容错级别
$matrixPointSize = 6.2068965517241379310344827586207; //生成图片大小
//生成二维码图片
\QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
}
return $filename2;
}
/*距离格式化2*/
function distanceFormatGeo($distance)
{
if(empty($distance)) return -1;
$distance = floatval($distance);
if ($distance < 1) {
$a = floor($distance * 1000);
$a = $a == 0 ? 1 : $a;
return $a . '米';
} elseif ($distance < 100) {
$b = number_format($distance, 1);
if(($b*10) % 10 != 0){
return $b . 'km'; //保留一位小数,会四舍五入
}
return floor($b) . 'km';
}
return floor($distance) . 'km'; //保留一位小数,会四舍五入
}
/* 校验签名 */
function checkSign($data, $sign)
{
//废弃,走框架入口校验
return 1;
$key = DI()->config->get('app.sign_key');
$str = '';
ksort($data);
foreach ($data as $k => $v) {
$str .= $k . '=' . $v . '&';
}
$str .= $key;
$newsign = md5($str);
/*var_dump($newsign);
die;*/
if ($sign == $newsign) {
return 1;
}
return 0;
}
/* 计算年龄 */
function datediffage($before, $after)
{
if ($before > $after) {
$b = getdate($after);
$a = getdate($before);
} else {
$b = getdate($before);
$a = getdate($after);
}
$n = array(1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
$y = $m = $d = 0;
if ($a[‘mday’] >= $b[‘mday’]) { //天相减为正
if ($a[‘mon’] >= $b[‘mon’]) {//月相减为正
$y = $a[‘year’] – $b[‘year’];
$m = $a[‘mon’] – $b[‘mon’];
} else { //月相减为负,借年
$y = $a[‘year’] – $b[‘year’] – 1;
$m = $a[‘mon’] – $b[‘mon’] + 12;
}
$d = $a[‘mday’] – $b[‘mday’];
} else { //天相减为负,借月
if ($a[‘mon’] == 1) { //1月,借年
$y = $a[‘year’] – $b[‘year’] – 1;
$m = $a[‘mon’] – $b[‘mon’] + 12;
$d = $a[‘mday’] – $b[‘mday’] + $n[12];
} else {
if ($a[‘mon’] == 3) { //3月,判断闰年取得2月天数
$d = $a[‘mday’] – $b[‘mday’] + ($a[‘year’] % 4 == 0 ? 29 : 28);
} else {
$d = $a[‘mday’] – $b[‘mday’] + $n[$a[‘mon’] – 1];
}
if ($a[‘mon’] >= $b[‘mon’] + 1) { //借月后,月相减为正
$y = $a[‘year’] – $b[‘year’];
$m = $a[‘mon’] – $b[‘mon’] – 1;
} else { //借月后,月相减为负,借年
$y = $a[‘year’] – $b[‘year’] – 1;
$m = $a[‘mon’] – $b[‘mon’] + 12 – 1;
}
}
}
return (string)$y;
}
/* 时长格式化 */
function getSeconds($cha, $type = 0)
{
if ($cha < 0) {
return '0秒';
}
$iz = floor($cha / 60);
$hz = floor($iz / 60);
$dz = floor($hz / 24);
/* 秒 */
$s = $cha % 60;
/* 分 */
$i = floor($iz % 60);
/* 时 */
$h = floor($hz / 24);
/* 天 */
if ($type == 1) {
if ($s < 10) {
$s = '0' . $s;
}
if ($i < 10) {
$i = '0' . $i;
}
if ($h < 10) {
$h = '0' . $h;
}
if ($hz < 10) {
$hz = '0' . $hz;
}
return $hz . ':' . $i . ':' . $s;
}
if ($cha < 60) {
return $cha . '秒';
} else if ($iz < 60) {
return $iz . '分钟' . $s . '秒';
} else if ($hz < 24) {
return $hz . '小时' . $i . '分钟' . $s . '秒';
} else {
return $dz . '天' . $h . '小时' . $i . '分钟' . $s . '秒';
}
}
/* 数字格式化 */
function NumberFormat($num)
{
if ($num < 10000) {
} else if ($num < 1000000) {
$num = round($num / 10000, 2) . '万';
} else if ($num < 100000000) {
$num = round($num / 10000, 1) . '万';
} else if ($num < 10000000000) {
$num = round($num / 100000000, 2) . '亿';
} else {
$num = round($num / 100000000, 1) . '亿';
}
return $num;
}
/* 生成邀请码 */
function createCode($len=6,$format='ALL'){
$is_abc = $is_numer = 0;
$password = $tmp ='';
switch($format){
case 'ALL':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
break;
case 'ALL2':
$chars='ABCDEFGHJKLMNPQRSTUVWXYZ0123456789';
break;
case 'CHAR':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
break;
case 'NUMBER':
$chars='0123456789';
break;
default :
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
break;
}
while(strlen($password)<$len){
$tmp =substr($chars,(mt_rand()%strlen($chars)),1);
if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
$is_numer = 1;
}
if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
$is_abc = 1;
}
$password.= $tmp;
}
if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
$password = createCode($len,$format);
}
if($password!=''){
$oneinfo=Db::name("agent_code")->field("uid")->where("code='{$password}'")->find();
if(!$oneinfo){
return $password;
}
}
$password = createCode($len,$format);
return $password;
}
/* 过滤字符 */
function filterField($field)
{
$configpri = getConfigPri();
$sensitive_field = $configpri[‘sensitive_field’];
$sensitive = explode(",", $sensitive_field);
$replace = array();
$preg = array();
foreach ($sensitive as $k => $v) {
if ($v != '') {
$re = '';
$num = mb_strlen($v);
for ($i = 0; $i < $num; $i++) {
$re .= '*';
}
$replace[$k] = $re;
$preg[$k] = '/' . $v . '/';
} else {
unset($sensitive[$k]);
}
}
return preg_replace($preg, $replace, $field);
}
/* 时间差计算 */
function datetime($time)
{
$cha = time() – $time;
$iz = floor($cha / 60);
$hz = floor($iz / 60);
$dz = floor($hz / 24);
/* 秒 */
$s = $cha % 60;
/* 分 */
$i = floor($iz % 60);
/* 时 */
$h = floor($hz / 24);
/* 天 */
if ($cha < 60) {
return $cha . '秒前';
} else if ($iz < 60) {
return $iz . '分钟前';
} else if ($hz < 24) {
return $hz . '小时' . $i . '分钟前';
} else if ($dz < 30) {
return $dz . '天前';
} else {
return date("Y-m-d", $time);
}
}
/* 时间差计算 */
function datetimeNearby($time)
{
$cha = time() – $time;
$iz = floor($cha / 60);
$hz = floor($iz / 60);
$dz = floor($hz / 24);
/* 秒 */
$s = $cha % 60;
/* 分 */
$i = floor($iz % 60);
/* 时 */
$h = floor($hz / 24);
/* 天 */
if ($cha < 300) {
return T('Online');
} else if ($iz < 30) {
return T('Just online');
} else if ($hz < 1) {
return $i . T('minutes ago');
} else if ($hz < 24) {
return $hz . T('hour') . $i . T('minutes ago');
} else if ($dz < 3) {
return $dz . T('days ago');
} else {
return date("Y-m-d", $time);
}
}
/**
* @desc 根据两点间的经纬度计算距离
* @param float $lat 纬度值
* @param float $lng 经度值
*/
function getDistance($lat1, $lng1, $lat2, $lng2)
{
$earthRadius = 6371000; //近似地球半径 单位 米
/*
Convert these degrees to radians
to work with the formula
*/
$lat1 = ($lat1 * pi()) / 180;
$lng1 = ($lng1 * pi()) / 180;
$lat2 = ($lat2 * pi()) / 180;
$lng2 = ($lng2 * pi()) / 180;
$calcLongitude = $lng2 – $lng1;
$calcLatitude = $lat2 – $lat1;
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
$calculatedDistance = $earthRadius * $stepTwo;
$distance = $calculatedDistance / 1000;
if ($distance < 10) {
$rs = round($distance, 2);
} else if ($distance > 1000) {
$rs = '1000';
} else {
$rs = round($distance);
}
return $rs . 'km';
}
/* 去除emoji表情 */
function filterEmoji($str)
{
$str = preg_replace_callback(
'/./u',
function (array $match) {
return strlen($match[0]) >= 4 ? ” : $match[0];
},
$str);
return $str;
}
/**
*
* curl post/get请求
* @param $url string 请求地址
* @param $vars array post请求的参数
* @param $isJson bool 是否需要发送json数据类型的数据
*/
function curlRequest($url, $vars, $isJson = false)
{
$ch = curl_init();
$params[CURLOPT_URL] = $url; //请求url地址
$params[CURLOPT_HEADER] = false; //是否返回响应头信息
$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
$params[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1';
$postfields = '';
if (!$isJson) {
foreach ($vars as $key => $value) {
$postfields .= urlencode($key) . '=' . urlencode($value) . '&';
}
} else {
$postfields = json_encode($vars);
}
$params[CURLOPT_POST] = true;
$params[CURLOPT_POSTFIELDS] = $postfields;
//解决方案一 禁用证书验证
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSL_VERIFYHOST] = false;
curl_setopt_array($ch, $params); //传入curl参数
return curl_exec($ch); //执行
}
/* curl get请求 */
function curl_get($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
/* 检测文件后缀 */
function checkExt($filename)
{
$config = array("jpg", "png", "jpeg");
$ext = pathinfo(strip_tags($filename), PATHINFO_EXTENSION);
return empty($config) ? true : in_array(strtolower($ext), $config);
}
/* 密码加密 */
function setPass($pass)
{
$authcode = 'rCt52pF2cnnKNB3Hkp';
$pass = "###" . md5(md5($authcode . $pass));
return $pass;
}
/* 去除NULL 判断空处理 主要针对字符串类型*/
function checkNull($checkstr)
{
$checkstr = trim($checkstr);
$checkstr = urldecode($checkstr);
if (get_magic_quotes_gpc() == 0) {
$checkstr = addslashes($checkstr);
}
//$checkstr=htmlspecialchars($checkstr);
//$checkstr=filterEmoji($checkstr);
if (strstr($checkstr, 'null') || (!$checkstr && $checkstr != 0)) {
$str = '';
} else {
$str = $checkstr;
}
return $str;
}
function Post($curlPost, $url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
function xml_to_array($xml)
{
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
if (preg_match_all($reg, $xml, $matches)) {
$count = count($matches[0]);
for ($i = 0; $i < $count; $i++) {
$subxml = $matches[2][$i];
$key = $matches[1][$i];
if (preg_match($reg, $subxml)) {
$arr[$key] = xml_to_array($subxml);
} else {
$arr[$key] = $subxml;
}
}
}
return $arr;
}
/* 密码检查 */
function passcheck($user_pass)
{
/* 必须包含字母、数字 */
$preg = '/^(?=.*[A-Za-z])(?=.*[0-9])[a-zA-Z0-9~!@&%#_]{6,20}$/';
$isok = preg_match($preg, $user_pass);
if ($isok) {
return 1;
}
return 0;
}
/* 检验手机号 */
function checkMobile($mobile)
{
$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/", $mobile);
if ($ismobile) {
return 1;
} else {
return 0;
}
}
/* 随机数 */
function random($length = 6, $numeric = 0)
{
PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
if ($numeric) {
$hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) – 1));
} else {
$hash = '';
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
$max = strlen($chars) – 1;
for ($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
/**
* 二维数组根据某个字段排序
* @param array $array 要排序的数组
* @param string $keys 要排序的键字段
* @param string $sort 排序类型 SORT_ASC SORT_DESC
* @return array 排序后的数组
*/
function arraySort($array, $keys, $sort = SORT_ASC) {
$keysValue = [];
foreach ($array as $k => $v) {
$keysValue[$k] = $v[$keys];
}
array_multisort($keysValue, $sort, $array);
return $array;
}
/**
* 生成唯一文件名称
*/
function uuid()
{
$charid = md5(uniqid(mt_rand(), true));
$hyphen = chr(45);
$uuid = substr($charid, 0, 8) . $hyphen
. substr($charid, 8, 4) . $hyphen
. substr($charid, 12, 4) . $hyphen
. substr($charid, 16, 4) . $hyphen
. substr($charid, 20, 12);
return $uuid;
}
/**
* url的base64编码
* @param $str string 编码字符串
*/
function urlBase64Encode($str)
{
$find = array('+', '/');
$replace = array('-', '_');
return str_replace($find, $replace, base64_encode($str));
}
PHP Redis Geo 相关 函数 –开始
/**
* redis geo 添加
* @param $key
* @param $longitude
* @param $latitude
* @param $member
*/
function geoAdd($key, $longitude, $latitude, $member)
{
$isexist = DI()->redis->geoadd($key, $longitude, $latitude, $member);
return $isexist;
}
/**
* geo 距离
* @param $key
* @param $member1
* @param $member2
* @param null $unit
*/
function geoDist($key, $member1, $member2, $unit = null)
{
$isexist = DI()->redis->geodist($key, $member1, $member2, $unit);
return $isexist;
}
/**
* geo 取地理位置坐标
* @param $key
* @param mixed …$member
*/
function geoHash($key, …$member)
{
$isexist = DI()->redis->geohash($key, …$member);
return $isexist;
}
/**
* geo 指定名称之间距离
* @param string $key
* @param string $member
*/
function geoPos(string $key, string $member)
{
$isexist = DI()->redis->geopos($key, $member);
return $isexist;
}
/**
* geo 指定坐标中心范围内地点
* @param $key
* @param $longitude
* @param $latitude
* @param $radius
* @param $unit
* @param array|null $options
*/
function geoRadius($key, $longitude, $latitude, $radius, $unit, array $options = null)
{
$isexist = DI()->redis->georadius($key, $longitude, $latitude, $radius, $unit, $options);
return $isexist;
}
/**
* geo 指定位置中心范围内地点
* @param $key
* @param $member
* @param $radius
* @param $units
* @param array|null $options
* @return array
*/
function geoRadiusByMember($key, $member, $radius, $units, array $options = null)
{
$isexist = DI()->redis->georadiusbymember($key, $member, $radius, $units, $options);
return $isexist;
}
PHP Redis Geo 相关 函数 — 结束
PHP Redis 链接 (π框架)– 开始
/* Redis链接 */
function connectionRedis()
{
$REDIS_HOST = DI()->config->get('app.REDIS_HOST');
$REDIS_AUTH = DI()->config->get('app.REDIS_AUTH');
$REDIS_PORT = DI()->config->get('app.REDIS_PORT');
$redis = new Redis();
$redis->pconnect($REDIS_HOST, $REDIS_PORT);
$redis->auth($REDIS_AUTH);
return $redis;
}
/* 设置缓存 */
function setcache($key, $info)
{
$config = getConfigPri();
if ($config[‘cache_switch’] != 1) {
return 1;
}
DI()->redis->set($key, json_encode($info));
DI()->redis->expire($key, $config[‘cache_time’] ?? 60);
return 1;
}
/* 设置缓存 可自定义时间*/
function setcaches($key, $info, $time = 0)
{
DI()->redis->set($key, json_encode($info));
if ($time > 0) {
DI()->redis->expire($key, $time);
}
return 1;
}
/* 获取缓存 */
function getcache($key)
{
$config = getConfigPri();
if ($config[‘cache_switch’] != 1) {
$isexist = false;
} else {
$isexist = DI()->redis->Get($key);
}
return json_decode($isexist, true);
}
/* 获取缓存 不判断后台设置 */
function getcaches($key)
{
$isexist = DI()->redis->Get($key);
return json_decode($isexist, true);
}
/* 删除缓存 */
function delcache($key)
{
$isexist = DI()->redis->del($key);
return 1;
}
PHP Redis 链接 (π框架)– 结束