列表转树型
/*列表转树型*/
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root=0)
{
$tree = array();// 创建Tree
if(is_array($list))
{
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) $refer[$data[$pk]] =& $list[$key];
foreach ($list as $key => $data)
{
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId)
{
$tree[$data[$pk]] =& $list[$key];
} else {
if (isset($refer[$parentId]))
{
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
判断 是否json格式字符串
function IsJson($strJson)
{
json_decode($strJson);
return (json_last_error() === JSON_ERROR_NONE);
}
判断 客户端 是否支付宝
return stripos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient');
判断 客户端 是否微信端
return stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger');
判断 是否手机号
return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}|^19[\d]{9}$#', $mobile) ? true : false;
判断 客户端 是否手机端
function IsMobile()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$mobile_agents = array('240x320','acer','acoon','acs-','abacho','ahong','airness','alcatel','amoi','android','anywhereyougo.com','applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','benq','bilbo','bird','blackberry','blazer','bleu','cdm-','compal','coolpad','danger','dbtel','dopod','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess','gradiente','grundig','haier','hedy','hitachi','htc','huawei','hutchison','inno','ipad','ipaq','ipod','jbrowser','kddi','kgt','kwc','lenovo','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-','lge9','longcos','maemo','mercator','meridian','micromax','midp','mini','mitsu','mmm','mmp','mobi','mot-','moto','nec-','netfront','newgen','nexian','nf-browser','nintendo','nitro','nokia','nook','novarra','obigo','palm','panasonic','pantech','philips','phone','pg-','playstation','pocket','pt-','qc-','qtek','rover','sagem','sama','samu','sanyo','samsung','sch-','scooter','sec-','sendo','sgh-','sharp','siemens','sie-','softbank','sony','spice','sprint','spv','symbian','tablet','talkabout','tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','up.browser','utec','utstar','verykool','virgin','vk-','voda','voxtel','vx','wap','wellco','wig browser','wii','windows ce','wireless','xda','xde','zte');
$is_mobile = false;
foreach ($mobile_agents as $device)
{
if (stristr($user_agent,$device))
{
$is_mobile = true;
break;
}
}
return $is_mobile;
}
判断 身份证号码
/**
* 规则验证身份证函数
*/
function validateIdCard($value)
{
/*基本格式校验*/
if (!preg_match('/^\d{17}[0-9xX]$/', $value)) return false;
/*年月日位校验*/
$parsed = date_parse(substr($value, 6, 8));
if (!(isset($parsed['warning_count']) && $parsed['warning_count'] == 0)) return false;
$base = substr($value, 0, 17);
$factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
$tokens = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
$checkSum = 0;
for ($i=0; $i<17; $i++)
{
$checkSum += intval(substr($base, $i, 1)) * $factor[$i];
}
$mod = $checkSum % 11;
$token = $tokens[$mod];
$lastChar = strtoupper(substr($value, 17, 1));
/*最后一位校验位校验*/
return ($lastChar === $token);
}
/*
* 在线API验证接口文档:http://www.juhe.cn/docs/103
*/
判断 是否车牌号
function isCarLicense($license)
{
if (empty($license)) return false;
/*#匹配民用车牌和使馆车牌
# 判断标准
# 1,第一位为汉字省份缩写
# 2,第二位为大写字母城市编码
# 3,后面是5位仅含字母和数字的组合*/
{
$regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新使]{1}[A-Z]{1}[0-9a-zA-Z]{5}$/u";
preg_match($regular, $license, $match);
if (isset($match[0])) return true;
}
/*#匹配特种车牌(挂,警,学,领,港,澳)
#参考 https://wenku.baidu.com/view/4573909a964bcf84b9d57bc5.html*/
{
$regular = '/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[0-9a-zA-Z]{4}[挂警学领港澳]{1}$/u';
preg_match($regular, $license, $match);
if (isset($match[0])) return true;
}
/*#匹配武警车牌
#参考 https://wenku.baidu.com/view/7fe0b333aaea998fcc220e48.html*/
{
$regular = '/^WJ[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]?[0-9a-zA-Z]{5}$/ui';
preg_match($regular, $license, $match);
if (isset($match[0])) return true;
}
/*#匹配军牌
#参考 http://auto.sina.com.cn/service/2013-05-03/18111149551.shtml*/
{
$regular = "/[A-Z]{2}[0-9]{5}$/";
preg_match($regular, $license, $match);
if (isset($match[0])) return true;
}
return false;
}
判断 浏览器类型
function BrowserType()
{
$browser = 'other';
if(strpos($_SERVER["HTTP_USER_AGENT"], "TheWorld") || strpos($_SERVER["HTTP_USER_AGENT"], "QIHU THEWORLD"))
{
$browser = 'world';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "Maxthon"))
{
$browser = 'aoyou';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler"))
{
/*or (strpos($_SERVER["HTTP_USER_AGENT"], "Trident") AND strpos($_SERVER["HTTP_USER_AGENT"], "SLCC2"))*/
$browser = 'telcent';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "SE 2") AND strpos($_SERVER["HTTP_USER_AGENT"], "MetaSr"))
{
$browser = 'sogou';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "360SE") AND !strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler"))
{
$browser = '360';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "QIHU 360EE") AND !strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler"))
{
$browser = '360';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 9.0"))
{
$browser = 'ie9';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 8.0"))
{
$browser = 'ie8';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 7.0"))
{
$browser = 'ie7';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 6.0"))
{
$browser = 'ie6';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "Firefox"))
{
$browser = 'firefox';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "Chrome"))
{
$browser = 'chrome';
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"], "Safari"))
{
$browser = 'safari';
}
redirect("/start/$browser");exit;
}
换算 空间大小
function SpaceConversion($number)
{
$num = strlen($number);
if ($num > 9) {
$num = $num - 9;
return substr($number,0,$num).'GB';
} elseif ($num > 6) {
$num = $num - 6;
return substr($number,0,$num).'MB';
} elseif ($num > 3) {
$num = $num -3;
return substr($number,0,$num).'KB';
} else {
return $number.'B';
}
}
换算 距离当前时间的字符串
/**
* 显示距离当前时间的字符串
* @param $time
* @return false|string
* @throws Exception
*/
function TranTime($time)
{
if(!is_numeric($time))
{
if(!strtotime($time)) throw new Exception('The parameters are not in format');
$time = strtotime($time);
}
$rtime = date("m-d",$time);
if($time <= time())
{
//之前
$time = time() - $time;
if ($time < 60)
{
$str = '刚刚';
}
elseif ($time < 60 * 60)
{
$min = floor($time/60);
$str = $min.'分钟前';
}
elseif ($time < 60 * 60 * 24)
{
$h = floor($time/(60*60));
$str = $h.'小时前';
}
elseif ($time < 60 * 60 * 24 * 3)
{
$d = floor($time/(60*60*24));
$d==1 ? $str = '昨天': $str = '前天';
}
else {
$str = $rtime;
}
return $str;
}
elseif ($time >= time())
{
//之后
$time = $time - time();
if ($time < 60)
{
$str = '刚刚';
}
elseif ($time < 60 * 60)
{
$min = floor($time/60);
$str = $min.'分钟后';
}
elseif ($time < 60 * 60 * 24)
{
$h = floor($time/(60*60));
$str = $h.'小时后';
}
elseif ($time < 60 * 60 * 24 * 3)
{
$d = floor($time/(60*60*24));
$d==1 ? $str = '明天': $str = '后天';
}
else {
$d = floor($time/(60*60*24));
$str = $d.'天后';
}
return $str;
}
}
加密/解密函数
/**
* 加密函数
*/
function encode($str,$key)
{
$res = base64_encode($str);
$code = $res^$key;
return $code;
}
/**
* 解密函数
*/
function decode($str,$key)
{
return base64_decode($str^$key);
}
各种加密方法
/**
* 盐值加密
* @param $string 字符串
* @param $number 加密等级
* @param $salt string 盐值
* @return string leng: 1=32,2=64,3=128,4=40,5=60,6=60
*/
function Pwd_encode($string,$number,$salt='salt')
{
#B-crypt盐值特殊处理
if($number == 5 && defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH)
{
$salt = '$2y$11$' . substr(md5($salt), 0, 22);
}
$pwd = $string.$salt;
#Password Hashing API
if(version_compare(PHP_VERSION,'5.5.0','>') && $number === 6)
{
// length:60
return password_hash($pwd, PASSWORD_DEFAULT);
}
switch ($number){
//md5 length:32
case 1:
$pwd = md5($pwd);break;
//sha256 length:64
case 2:
$pwd = hash('sha256', $pwd);break;
//sha512 length:128
case 3:
$pwd = hash('sha512',$pwd);break;
//sha1 length:40
case 4:
$pwd = sha1($pwd);break;
//B-crypt length:60
case 5:
$pwd = crypt($pwd,$salt);break;
default:
//md5 length:32
$pwd = md5($pwd);break;
}
return $pwd;
}
通过goole Api以经纬度获取城市名
function curlGet( $latlng )
{
$url = "http://maps.google.com/maps/api/geocode/json?latlng={$latlng}&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); /*跳过证书检查*/
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); /*从证书中检查SSL加密算法是否存在*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output);
}
自动捕获Fatal Error
/**
* 自动捕获Fatal Error
*/
register_shutdown_function( "fatal_handler" );/*注册一个callback方法*/
set_error_handler("error_handler");/* 设置用户自定义的错误处理函数*/
define('E_FATAL', E_ERROR | E_USER_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR| E_PARSE );
//获取fatal error
function fatal_handler()
{
$error = error_get_last();
if($error && ($error["type"]===($error["type"] & E_FATAL)))
{
error_handler($error["type"],$error["message"],$error["file"],$error["line"]);
}
}
/*获取所有的error*/
function error_handler($errno,$errstr,$errfile,$errline)
{
$str=<<
Xml转换成Json
return json_encode(simplexml_load_string($xml_info));
二维数组排序
/**
* 二维数组排序
* @param $arrays array 数组 | 随后的每一个参数可能是数组,也可能是下面的排序顺序标志
* @param $sort_key mixed
* @param $sort_order mixed SORT_ASC - 默认,按升序排列。(A-Z)
* SORT_DESC - 按降序排列。(Z-A)
* @param $sort_type mixed SORT_REGULAR - 默认。将每一项按常规顺序排列。
* SORT_NUMERIC - 将每一项按数字顺序排列。
* SORT_STRING - 将每一项按字母顺序排列
* @return array
*/
function Sort2Array($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC )
{
if(is_array($arrays))
{
foreach ($arrays as $array)
{
if(is_array($array))
{
$key_arrays[] = $array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
return $arrays;
}
二分查找算法
/**
* 二分查找算法
* -----------------------------------------------------------------------------------------
* 优点是比较次数少,查找速度快,平均性能好,占用系统内存较少
* 缺点是要求待查表为有序表,且插入删除困难
* 折半查找方法适用于不经常变动而查找频繁的有序列表
* 首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;
* 否则利用中间位置记录将表分成前、后两个子表,
* 如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
* 重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功
* ------------------------------------------------------------------------------------------
* @param array $a 检索的列表,必须一维,有序列表
* @param number $x 检索的值
* @return number 返回列表键名,查找失败返回-1
*/
function BinSearch($x,$a)
{
$c=count($a);
$lower=0;
$high=$c-1;
while($lower<=$high)
{
$middle=intval(($lower+$high)/2);
if($a[$middle]>$x)
{
$high=$middle-1;
}
elseif($a[$middle]<$x)
{
$lower=$middle+1;
} else {
return $middle;
}
}
return -1;
}
array_column() php5.5 以下版本使用
/**
* array_column php5.5 以下版本使用
* @param $input array 规定要使用的多维数组(记录集)。
* @param $columnKey mixed 需要返回值的列。
* @param $indexKey mixed 可选。用作返回数组的索引/键的列。
* @return array
*
*/
function Column($input, $columnKey, $indexKey = NULL)
{
$columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
$indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
$indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
$result = array();
foreach ((array)$input AS $key => $row)
{
if ($columnKeyIsNumber)
{
$tmp = array_slice($row, $columnKey, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
}
else
{
$tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
}
if ( ! $indexKeyIsNull)
{
if ($indexKeyIsNumber)
{
$key = array_slice($row, $indexKey, 1);
$key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
$key = is_null($key) ? 0 : $key;
}
else
{
$key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
大转盘、摇一摇等抽奖
/**
* 抽奖算法
* @param $array array 奖品集合信息列表
* @param $chance string 中奖概率字段名
* @param $prize_id string 奖品索引字段名
* @return mixed 奖品索引字段值
*/
function RandPrize($array,$chance,$prize_id)
{
//整合概率
foreach( $array as $k => $v )
{
//使用新数组item : 中奖率 * 倍率得到分母200
$item[$k+1] = $v[$chance] * 2;
}
//计算出分母
$num = intval(array_sum($item));
$id = false;
foreach( $item as $k => $v )
{
//概率区间(正整数)
$rand = mt_rand(1, 200);
if( $rand <= $v ){
$id = $array[$k-1][$prize_id];
return $id;
//结束循环,返回结果
break;
}else{
//使算法必出一个结果
$num-=$v;
}
}
if(!$id){return $id;}
}
简单的字符串导出表格,CSV格式
/**
*Excel 导出 CSV格式
* @param $filename string 导出文件名
* @param $string string 逗号连接的字符串
* 使用前需处理:
* $str="编号,姓名,年龄\n";//文档第一行
* foreach($data as $key=>$val)
* {
* $name=$val['name'];//中文转码
* $detail=$val['detail'];
* $code=$val['code'];
* $str .=$name.','.$detail.','.$code."\n";//赋一行的值
* }
*/
function Excel_export($filename,$string='')
{
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo $string;
}
CURL
function RequestCurl($url, $params = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if (!empty($params)) {
if(is_array($params)){
/*如果传的是数组,就要进行对参数进行 &拼接*/
$params=http_build_query($params);
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
$body = curl_exec($ch);
curl_close($ch);
return $body;
}
获取指定目录下的子目录 或 指定后缀的子文件
/**
* 获取指定目录下的子目录 或 指定后缀的子文件
* @param string $path 指定目录路径
* @param string $suffix 文件后缀,不写默认为获取子目录
* @throws string @Exception
* @return array
*/
function RetrievalDir($path, $suffix='')
{
$path = iconv('utf-8', 'gbk', $path);
if(!is_dir($path)){
throw new Exception("path is not a directory");
}
$arr = array('dir'=>array(),'file'=>array());
$hd = opendir($path);
while(($file = readdir($hd))!==false){
if($file=='.'||$file=='..') {continue;}
if(is_dir($path.'/'.$file)){
$arr['dir'][] = iconv('gbk','utf-8',$file);
}else if(is_file($path."/".$file)){
$pathinfo = pathinfo($file);
if($suffix && $pathinfo['extension'] == $suffix){
$arr['file'][] = iconv('gbk','utf-8',$file);
}
}
}
closedir($hd);
return $arr;
}
获取Url后缀
function GetExtByUrl($filename)
{
return strrchr($filename,'.');
}
PHP 返回404
/*PHP 返回404*/
function Re404()
{
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
exit;
}
去除换行
return str_replace(PHP_EOL, '', $str);
PHP 获取中文字符拼音首字母
function getFirstCharter($str)
{
if(empty($str)) return '';
$fchar=ord($str{0});
if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
$s1=iconv('UTF-8','gb2312',$str);
$s2=iconv('gb2312','UTF-8',$s1);
$s=$s2==$str?$s1:$str;
$asc=ord($s{0})*256+ord($s{1})-65536;
if($asc>=-20319&&$asc<=-20284) return 'A';
if($asc>=-20283&&$asc<=-19776) return 'B';
if($asc>=-19775&&$asc<=-19219) return 'C';
if($asc>=-19218&&$asc<=-18711) return 'D';
if($asc>=-18710&&$asc<=-18527) return 'E';
if($asc>=-18526&&$asc<=-18240) return 'F';
if($asc>=-18239&&$asc<=-17923) return 'G';
if($asc>=-17922&&$asc<=-17418) return 'H';
if($asc>=-17417&&$asc<=-16475) return 'J';
if($asc>=-16474&&$asc<=-16213) return 'K';
if($asc>=-16212&&$asc<=-15641) return 'L';
if($asc>=-15640&&$asc<=-15166) return 'M';
if($asc>=-15165&&$asc<=-14923) return 'N';
if($asc>=-14922&&$asc<=-14915) return 'O';
if($asc>=-14914&&$asc<=-14631) return 'P';
if($asc>=-14630&&$asc<=-14150) return 'Q';
if($asc>=-14149&&$asc<=-14091) return 'R';
if($asc>=-14090&&$asc<=-13319) return 'S';
if($asc>=-13318&&$asc<=-12839) return 'T';
if($asc>=-12838&&$asc<=-12557) return 'W';
if($asc>=-12556&&$asc<=-11848) return 'X';
if($asc>=-11847&&$asc<=-11056) return 'Y';
if($asc>=-11055&&$asc<=-10247) return 'Z';
return null;
}