<?php
namespace isslib\Util;
use think\Config; /**
* 常用工具类
* User: xaxiong
* Date: 2016/12/19
* Time: 13:47
*/
class Tool{ /**
* 简单加密处理函数
* @param $data
* @return string
*/
public static function encodeData($data){
return urlencode(json_encode($data));
} /**
* 简单解密处理函数
* @param $data
* @return mixed
*/
public static function decodeData($data){
return json_decode(urldecode($data),true);
} public static function getPrefix($mprefix=''){
return empty($mprefix)?Config::get('database.prefix'):Config::get('database.prefix').Config::get('database.mprefix')[$mprefix];
} /**
* 对excel里的日期进行格式转化
* @param $val 数据
* @param $format 格式
* @return string
*/
public static function GetExceDate($val,$format){
if(!empty($val)) {
$jd = \GregorianToJD(1, 1, 1970);
$date = \JDToGregorian($jd + intval($val) - 25569);
// list($month, $day, $year) = explode('/',$date);
if (!empty($format)) $date = date($format, strtotime($date));
return $date;
}else{
return null;
}
} /**
* 格式化数字
* @param $number 要格式化的数值
* @param $type 类型 normal,electric
* @param $type 单位后缀
*/
public static function numberFormat($number,$type='normal',$extUnit='')
{
/**
* @var array 数据格式化类型
*/
$FORMAT_TYPE=array(
'normal'=>array(
array(
'base'=>100000000,
'unit'=>'亿'
),
array(
'base'=>10000,
'unit'=>'万'
),
array(
'base'=>1000,
'unit'=>'千'
),
array(
'base'=>1,
'unit'=>''
)
),
'electric'=>array(
array(
'base'=>1000000000000,
'unit'=>'TW'
),
array(
'base'=>1000000000,
'unit'=>'GW'
),
array(
'base'=>1000000,
'unit'=>'MW'
),
array(
'base'=>1000,
'unit'=>'KW'
),
array(
'base'=>1,
'unit'=>'W'
)
)
); $FORMAT_TYPE_ITEM=$FORMAT_TYPE[$type];
//$keys=array_keys($FORMAT_TYPE_ITEM);
//var_dump($FORMAT_TYPE_ITEM[$keys[0]]);exit();
if(empty($number)){
$arr['value']= 0;
$arr['unit']='';
$arr['base']=1;
return $arr;
}
return self::getMaxUnit($number,$FORMAT_TYPE_ITEM,$extUnit); } /**
* 获取最大单位数据
* @param $number 数字
* @param $AllArr 数据类型配置
* @param string $extUnit 单位
* @param array $currArr 当前数据
* @return array
*/
public static function getMaxUnit($number,$AllArr,$extUnit='',$currArr=array()){
//if($index>count($desArr)) return $returnArr;
if(empty($currArr)){
$currArr=$AllArr[0];
}
$key=$currArr['base'];
$value=$currArr['unit']; $leaveNum=$number/$key;
$resdata=array();
//arrayStep::getInstance($AllArr)->setCurrent($key);
if($leaveNum > 0 && $leaveNum < 1){
//$nextArr=arrayStep::getInstance($AllArr)->getNext();
$nextArr=next($AllArr);//var_dump($nextArr);
$data=self::getMaxUnit($number,$AllArr,$extUnit,$nextArr);
if(!empty($data))return $data;
}else{
$resdata= array(
'value'=>number_format(round($leaveNum)),
'unit'=>$value.$extUnit,
'base'=>$key
);
//var_dump($resdata);
return $resdata;
exit();
}
} /**
* 无限极分类树的生成
* @param $list 数据
* @param string $pk key名称
* @param string $pid 父级编号
* @param string $child
* @param int $root
* @return array
*/
public static function list_to_tree($list, $pk='id',$pid = 'pid',$child = 'child',$root=0) {
// 创建Tree
$tree = array();
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[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
} /**
* GET调用接口获取返回值
* @param $url url地址
* @param array $header 请求头配置
* @return mixed
*/
public function curlGET($url,$header=array()){ $_SESSION['issTcSession']['get'][$url]['url'] = $url;
$_SESSION['issTcSession']['get'][$url]['header'] = $header;
// echo $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
$starttime=microtime(true);
$temp = curl_exec($ch);
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($ch);
return $temp;
} /**
* POST调用接口获取返回值
* @param $url url地址
* @param string $data 参数
* @param array $header 请求头
* @return mixed
*/
public function curlPOST($url,$data='',$header=array()){ $_SESSION['issTcSession']['post'][$url]['url'] = $url;
$_SESSION['issTcSession']['post'][$url]['data'] = $data;
$_SESSION['issTcSession']['post'][$url]['header'] = $header;
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 $starttime=microtime(true);
$tmpInfo = curl_exec($curl); // 执行操作
// if (curl_errno($curl)) {
// echo 'Errno'.curl_error($curl);
// }
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
} /**
* json数据返回格式化
* @param $data 数据
* @param string $status 状态
* @param string $errorCode 错误代码
* @param string $message 消息
* @param null $total 数据条数
*/
public function jsonReturn($data,$status='1',$errorCode='1',$message='',$total=null)
{ if($data)
{
$json['status'] = 1;
$json['errorCode'] = $errorCode;
$json['errorMsg'] = '请求成功';
if($total)
{
$json['total'] = $total;
}
else
{
$json['total'] = count($data);
}
$json['data'] = $data;
}
else
{
if($status != '1')
{
$json['status'] = $status;
$json['errorCode'] = $errorCode;
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
else
{
$json['status'] = '0';
$json['errorCode'] = '0';
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
$json['total'] = '0';
$json['data'] = array();
}
header("Content-type: application/json");
echo json_encode($json); } /**
* 保留小数
* @param $number 数字
* @param int $num 几位小数
* @return float|int
*/
public function decimal($number,$num=1){
$number = round($number,$num);
$number1 = intval($number);
$number2 = $number > $number1 ? $number : $number1;
return $number2; } /**
* 数组排序
* @param $arr 数组
* @param $keys key名
* @param string $type 排序类型 asc,desc
* @param int $is0
* @param int $isK
* @return array
*/
function arraySort($arr, $keys, $type = 'asc',$is0=0,$isK=0) {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v){
$keysvalue[$k] = $v[$keys];
}
$type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
reset($keysvalue);
foreach ($keysvalue as $k => $v) { if($isK == 1)
{
$new_array[$k] = $arr[$k];
}
else
{
$new_array[] = $arr[$k];
} }
if($is0 == 1)
{
foreach($new_array as $vo_is0)
{
if($vo_is0[$keys] > 0){
$new_array_s[] = $vo_is0;
}
}
return $new_array_s;
}
return $new_array;
} /**
* 判断是否 为空 给 后端数据转成null
* @param $data
* @param int $isStr 0表示不转字符串,1:表示传成字符串
* @return mixed
*/
function arrIsNull($data,$isStr=0)
{
foreach($data as $k=>&$vo)
{
if(empty($vo) && ($k != 'startRow') && ($k != 'endRow') && ($k != 'education'))
{
$vo = null;
}else{
if($isStr){
$vo .= "";
}
}
}
return $data;
} /**
* 着色
* @param $colorarr
* @param $data
* @return mixed
*/
function color2data($colorarr,$data){
$count = count($colorarr);
$count_data = count($data);
$d = intval($count_data/$count);
$d = $d <= 1 ? 1 : $d;
$c = 0;
$n = 1;
foreach($data as &$vo)
{
$temp['style'] = 'esriSFSSolid';
$temp['color'] = $colorarr[$c];
$outline['color'] = array(106, 212, 238,255);
$outline['width'] = 1;
$temp['outline'] = $outline;
$vo['coverStyle'] =$temp;
if($n == $d)
{
if($c < $count-1)
{
$c++;
}
$n = 1;
}
else
{
$n++;
}
}
return $data;
} /**
* 截取字符串
* @param $str
* @param $start
* @param $lenth
* @return string
*/
public function subStr($str, $start, $lenth)
{
$str1 = mb_substr($str,$start,$lenth,'UTF8');
return $str==$str1 ? $str : $str1.'...';
} /**
* 截取字符串
* @param $str
* @return int
*/
public function str2num($str)
{
$num1 = (int)$str;
if($num1 == $str)
{ return $num1;
}
else
{
return $str;
} } /**
* 字符串转数组转字符串
* @param $data
* @return mixed
*/
public function str2arr2str($data){
foreach($data as &$vo){
foreach($vo as &$vo1){
if(is_array($vo1))
{
$vo1 = json_encode($vo1);
// $vo1 = implode(',',$vo1);
}
}
}
return $data;
} function letter($value)
{
$letter = '';
do {
$letter = chr(65 + ($value % 26)) . $letter;
$temp = intval($value / 26);
if ($temp > 0) {
$value = $value - 26;
}
$value = intval($value / 26);
} while ($temp != 0);
return $letter;
} /**
* 调试函数
* @param unknown $str 要叠加字符的变量名
* @param unknown $addstr 要添加的字符
* @param string $ifdel 是否将之前的变量清空
* @return string
*/
public static function halt($logFile,$str,$ifdel=false)
{
header("Content-type: text/html; charset=utf-8");
$logname = C('SOURCE_DATA')['logs_dir'] . $logFile . '-' . date("Ymd") . '.html';
$tmpstr = date("Y-m-d h:i:sa") . ' '; if ($ifdel) {
//清除日志文件内容
@file_put_contents($logname, "");
}
if (!empty($str)) {
$tmpstr .= '--' . $str;
}
try {
//将日导写入日导文件
self::writeFile($logname, $tmpstr . "\r\n", 'a+');
} catch (Exception $e) {
echo '写入日志出现错误!,错误内容为:' . $e->getMessage();
//$this->writeFile($logname,$str.'Error:'.$e);
}
} /**
* 写文件
* @param string $file 文件路径
* @param string $str 写入内容
* @param char $mode 写入模式
*/
public static function writeFile($file,$str,$mode='w')
{
$oldmask = @umask(0);
$fp = @fopen($file,$mode);
@flock($fp, 3);
if(!$fp)
{
Return false;
}
else
{
@fwrite($fp,$str);
@fclose($fp);
@umask($oldmask);
Return true;
}
} /**
* gbk 转 utf8
* @param $str
* @return string
*/
public static function gbk_to_utf8($str){
return mb_convert_encoding($str, 'utf-8', 'gbk');
} /**
* utf8 转 gbk
* @param $str
* @return string
*/
public static function utf8_to_gbk($str){
return mb_convert_encoding($str, 'gbk', 'utf-8');
} /**
* 是否为windows操作系统,
* @return bool true:windows,false:其它操作系统
*/
function isWinOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') return true;
else return false;
}
/**
* 获取当前操作系统
* @return string
*/
function getOS(){
$os='';
$Agent=$_SERVER['HTTP_USER_AGENT'];
if (eregi('win',$Agent)&&strpos($Agent, '95')){
$os='Windows 95';
}elseif(eregi('win 9x',$Agent)&&strpos($Agent, '4.90')){
$os='Windows ME';
}elseif(eregi('win',$Agent)&&ereg('98',$Agent)){
$os='Windows 98';
}elseif(eregi('win',$Agent)&&eregi('nt 5.0',$Agent)){
$os='Windows 2000';
}elseif(eregi('win',$Agent)&&eregi('nt 6.0',$Agent)){
$os='Windows Vista';
}elseif(eregi('win',$Agent)&&eregi('nt 6.1',$Agent)){
$os='Windows 7';
}elseif(eregi('win',$Agent)&&eregi('nt 5.1',$Agent)){
$os='Windows XP';
}elseif(eregi('win',$Agent)&&eregi('nt',$Agent)){
$os='Windows NT';
}elseif(eregi('win',$Agent)&&ereg('32',$Agent)){
$os='Windows 32';
}elseif(eregi('linux',$Agent)){
$os='Linux';
}elseif(eregi('unix',$Agent)){
$os='Unix';
}else if(eregi('sun',$Agent)&&eregi('os',$Agent)){
$os='SunOS';
}elseif(eregi('ibm',$Agent)&&eregi('os',$Agent)){
$os='IBM OS/2';
}elseif(eregi('Mac',$Agent)&&eregi('PC',$Agent)){
$os='Macintosh';
}elseif(eregi('PowerPC',$Agent)){
$os='PowerPC';
}elseif(eregi('AIX',$Agent)){
$os='AIX';
}elseif(eregi('HPUX',$Agent)){
$os='HPUX';
}elseif(eregi('NetBSD',$Agent)){
$os='NetBSD';
}elseif(eregi('BSD',$Agent)){
$os='BSD';
}elseif(ereg('OSF1',$Agent)){
$os='OSF1';
}elseif(ereg('IRIX',$Agent)){
$os='IRIX';
}elseif(eregi('FreeBSD',$Agent)){
$os='FreeBSD';
}elseif($os==''){
$os='Unknown';
}
return $os;
} } /**对excel里的日期进行格式转化*/
function GetData($val){
$jd = \GregorianToJD(1, 1, 1970);
$gregorian = \JDToGregorian($jd+intval($val)-25569);
return $gregorian;/**显示格式为 “月/日/年” */
} /*根据数组中的某个键值大小进行排序,仅支持二维数组
@param array $array 排序数组
@param string $key 键值
@param bool $asc 默认正序
@return array 排序后数组*/ function arraySortByKey(array $array, $key, $asc = true) {
$result = array(); // 整理出准备排序的数组
$iddata=array();
$baifendata=array(); foreach ( $array as $k => &$v ) {
$values[$k] = isset($v[$key]) ? $v[$key] : ''; }
unset($v); // 对需要排序键值进行排序
$asc ? asort($values) : arsort($values); // 重新排列原有数组
foreach ( $values as $k => $v ) {
$result[$k] = $array[$k];
} $count=count($result);
foreach ($result as $key => $value) {
$iddata[]=$value['id'];
} for ($i = 0; $i < $count; $i++) {
$baifendata[]=round(($count - $i) / $count *100).'%';
}
$result =array_combine($iddata,$baifendata);
return $result; }
/**
* 无限级分类,直接获取节点树
* @param unknown $list 数据集合
* @param string $pk 主键字段
* @param string $pid 父节点id对应字段
* @param string $child 子节点id对应字段
* @param number $root 从第几级开始查询
* @return multitype:unknown
*/
function list_to_tree($list, $pk='id',$pid = 'pid',$child = 'child',$root=0) {
// 创建Tree
$tree = array();
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[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
//无限极分类返回列表行记录
/**
*
* @param unknown $cate_info_sort 返回的数据
* @param unknown $data 原始数据
* @param string $pk 表主键
* @param string $pid_name 表父字段id
* @param number $pid 开始的父字段id
* @param string $kk 分割线
*/
function cate_sort_role(&$cate_info_sort,$data,$pk='id',$pid_name="pid",$pid=0,$kk="|"){
foreach($data as $k=> $v){
if($v[$pid_name]==$pid){
foreach ($v as $ke=>$vl){
$cate_info_sort[$k][$ke] = $vl;
}
$cate_info_sort[$k]["kk"] = $kk;
$pos = strpos($kk, "--");
if($pos === false){
$cate_info_sort[$k]["sun"] = 0;
}else{
$cate_info_sort[$k]["sun"] = 1;
}
cate_sort_role($cate_info_sort,$data ,$pk,$pid_name,$v[$pk],"&nbsp;&nbsp;&nbsp;&nbsp;".$kk."--");
}
}
} /**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param boolean $adv 是否进行高级模式获取(有可能被伪装)
* @return mixed
*/
function get_client_ip($type = 0,$adv=false) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if($adv){
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
} /**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
function string2array($data) {
$data = trim($data);
if($data == '') return array();
if(strpos($data, 'array')===0){
@eval("\$array = $data;");
}else{
if(strpos($data, '{\\')===0) $data = stripslashes($data);
$array=json_decode($data,true);
// if(strtolower(CHARSET)=='gbk'){
// $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
// }
}
return $array;
}
/**
* 将数组转换为字符串
*
* @param array $data 数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
function array2string($data, $isformdata = 1) {
if($data == '' || empty($data)) return ''; if($isformdata) $data = new_stripslashes($data);
if(strtolower(CHARSET)=='gbk'){
$data = mult_iconv("GBK", "UTF-8", $data);
}
if (version_compare(PHP_VERSION,'5.3.0','<')){
return addslashes(json_encode($data));
}else{
return addslashes(json_encode($data,JSON_FORCE_OBJECT));
}
} /**
* 返回经htmlspecialchars处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
function new_html_special_chars($string) {
$encoding = 'utf-8';
if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
} function GetMonth($sign="1")
{
//得到系统的年月
$tmp_date=date("Ym");
//切割出年份
$tmp_year=substr($tmp_date,0,4);
//切割出月份
$tmp_mon =substr($tmp_date,4,2);
$tmp_nextmonth=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
$tmp_forwardmonth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
if($sign==0){
//得到当前月的下一个月
return $fm_next_month=date("Ym",$tmp_nextmonth);
}else{
//得到当前月的上一个月
return $fm_forward_month=date("Ym",$tmp_forwardmonth);
}
}
<?php
namespace isslib\Util;
use think\Config;
use think\Db;
use think\Debug; /**
* 常用工具类
* User: xaxiong
* Date: 2016/12/19
* Time: 13:47
*/
class Tool{ /**
* 简单加密处理函数
* @param $data
* @return string
*/
public static function encodeData($data){
return urlencode(json_encode($data));
} /**
* 简单解密处理函数
* @param $data
* @return mixed
*/
public static function decodeData($data){
return json_decode(urldecode($data),true);
} /**
* 获取数据表前缀
* @param string $mprefix 取值为:'origial':原始表;'dest':业务表;'system':系统表,标准知识库模型;'common':公共表
* @param bool $isprefix true 需要前缀,false不需要前缀
* @return mixed|string
*/
public static function getPrefix($mprefix='',$isprefix=true){
if($isprefix)
return empty($mprefix)?Config::get('database.prefix'):Config::get('database.prefix').Config::get('database.mprefix')[$mprefix];
else
return empty($mprefix)?'':Config::get('database.mprefix')[$mprefix];
} /**
* 对excel里的日期进行格式转化
* @param $val 数据
* @param $format 格式
* @return string
*/
public static function GetExceDate($val,$format){
if(!empty($val)) {
$jd = \GregorianToJD(1, 1, 1970);
$date = \JDToGregorian($jd + intval($val) - 25569);
// list($month, $day, $year) = explode('/',$date);
if (!empty($format)) $date = date($format, strtotime($date));
return $date;
}else{
return null;
}
} /**
* 格式化数字
* @param $number 要格式化的数值
* @param $type 类型 normal,electric
* @param $type 单位后缀
*/
public static function numberFormat($number,$type='normal',$extUnit='')
{
/**
* @var array 数据格式化类型
*/
$FORMAT_TYPE=array(
'normal'=>array(
array(
'base'=>100000000,
'unit'=>'亿'
),
array(
'base'=>10000,
'unit'=>'万'
),
array(
'base'=>1000,
'unit'=>'千'
),
array(
'base'=>1,
'unit'=>''
)
),
'electric'=>array(
array(
'base'=>1000000000000,
'unit'=>'TW'
),
array(
'base'=>1000000000,
'unit'=>'GW'
),
array(
'base'=>1000000,
'unit'=>'MW'
),
array(
'base'=>1000,
'unit'=>'KW'
),
array(
'base'=>1,
'unit'=>'W'
)
)
); $FORMAT_TYPE_ITEM=$FORMAT_TYPE[$type];
//$keys=array_keys($FORMAT_TYPE_ITEM);
//var_dump($FORMAT_TYPE_ITEM[$keys[0]]);exit();
if(empty($number)){
$arr['value']= 0;
$arr['unit']='';
$arr['base']=1;
return $arr;
}
return self::getMaxUnit($number,$FORMAT_TYPE_ITEM,$extUnit); } /**
* 获取最大单位数据
* @param $number 数字
* @param $AllArr 数据类型配置
* @param string $extUnit 单位
* @param array $currArr 当前数据
* @return array
*/
public static function getMaxUnit($number,$AllArr,$extUnit='',$currArr=array()){
//if($index>count($desArr)) return $returnArr;
if(empty($currArr)){
$currArr=$AllArr[0];
}
$key=$currArr['base'];
$value=$currArr['unit']; $leaveNum=$number/$key;
$resdata=array();
//arrayStep::getInstance($AllArr)->setCurrent($key);
if($leaveNum > 0 && $leaveNum < 1){
//$nextArr=arrayStep::getInstance($AllArr)->getNext();
$nextArr=next($AllArr);//var_dump($nextArr);
$data=self::getMaxUnit($number,$AllArr,$extUnit,$nextArr);
if(!empty($data))return $data;
}else{
$resdata= array(
'value'=>number_format(round($leaveNum)),
'unit'=>$value.$extUnit,
'base'=>$key
);
//var_dump($resdata);
return $resdata;
exit();
}
} /**
* 无限级分类,直接获取节点树
* @param unknown $list 数据集合
* @param string $pk 主键字段
* @param string $pid 父节点id对应字段
* @param string $child 子节点id对应字段
* @param number $root 从第几级开始查询
* @return multitype:unknown
*/
public static function list_to_tree($list, $pk='id',$pid = 'pid',$child = 'child',$root=0) {
// 创建Tree
$tree = array();
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[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
//无限极分类返回列表行记录
/**
*
* @param unknown $cate_info_sort 返回的数据
* @param unknown $data 原始数据
* @param string $pk 表主键
* @param string $pid_name 表父字段id
* @param number $pid 开始的父字段id
* @param string $kk 分割线
*/
public static function cate_sort(&$cate_info_sort,$data,$pk='id',$pid_name="pid",$pid=0,$kk="|"){
foreach($data as $k=> $v){
if($v[$pid_name]==$pid){
foreach ($v as $ke=>$vl){
$cate_info_sort[$k][$ke] = $vl;
}
$cate_info_sort[$k]["kk"] = $kk;
$pos = strpos($kk, "--");
if($pos === false){
$cate_info_sort[$k]["sun"] = 0;
}else{
$cate_info_sort[$k]["sun"] = 1;
}
self::cate_sort($cate_info_sort,$data ,$pk,$pid_name,$v[$pk],"&nbsp;&nbsp;&nbsp;&nbsp;".$kk."--");
}
}
} /**
* GET调用接口获取返回值
* @param $url url地址
* @param array $header 请求头配置
* @return mixed
*/
public static function curlGET($url,$header=array()){ $_SESSION['issTcSession']['get'][$url]['url'] = $url;
$_SESSION['issTcSession']['get'][$url]['header'] = $header;
// echo $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
$starttime=microtime(true);
$temp = curl_exec($ch);
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($ch);
return $temp;
} /**
* POST调用接口获取返回值
* @param $url url地址
* @param string $data 参数
* @param array $header 请求头
* @return mixed
*/
public static function curlPOST($url,$data='',$header=array()){ $_SESSION['issTcSession']['post'][$url]['url'] = $url;
$_SESSION['issTcSession']['post'][$url]['data'] = $data;
$_SESSION['issTcSession']['post'][$url]['header'] = $header;
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 $starttime=microtime(true);
$tmpInfo = curl_exec($curl); // 执行操作
// if (curl_errno($curl)) {
// echo 'Errno'.curl_error($curl);
// }
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
} /**
* json数据返回格式化
* @param $data 数据
* @param string $status 状态
* @param string $errorCode 错误代码
* @param string $message 消息
* @param null $total 数据条数
*/
public static function jsonReturn($data,$status='1',$errorCode='1',$message='',$total=null)
{ if($data)
{
$json['status'] = 1;
$json['errorCode'] = $errorCode;
$json['errorMsg'] = '请求成功';
if($total)
{
$json['total'] = $total;
}
else
{
$json['total'] = count($data);
}
$json['data'] = $data;
}
else
{
if($status != '1')
{
$json['status'] = $status;
$json['errorCode'] = $errorCode;
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
else
{
$json['status'] = '0';
$json['errorCode'] = '0';
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
$json['total'] = '0';
$json['data'] = array();
}
header("Content-type: application/json");
echo json_encode($json); } /**
* 保留小数
* @param $number 数字
* @param int $num 几位小数
* @return float|int
*/
public static function decimal($number,$num=1){
$number = round($number,$num);
$number1 = intval($number);
$number2 = $number > $number1 ? $number : $number1;
return $number2; } /**
* 数组排序
* @param $arr 数组
* @param $keys key名
* @param string $type 排序类型 asc,desc
* @param int $is0
* @param int $isK
* @return array
*/
public static function arraySort($arr, $keys, $type = 'asc',$is0=0,$isK=0) {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v){
$keysvalue[$k] = $v[$keys];
}
$type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
reset($keysvalue);
foreach ($keysvalue as $k => $v) { if($isK == 1)
{
$new_array[$k] = $arr[$k];
}
else
{
$new_array[] = $arr[$k];
} }
if($is0 == 1)
{
foreach($new_array as $vo_is0)
{
if($vo_is0[$keys] > 0){
$new_array_s[] = $vo_is0;
}
}
return $new_array_s;
}
return $new_array;
} /**
* 判断是否 为空 给 后端数据转成null
* @param $data
* @param int $isStr 0表示不转字符串,1:表示传成字符串
* @return mixed
*/
public static function arrIsNull($data,$isStr=0)
{
foreach($data as $k=>&$vo)
{
if(empty($vo) && ($k != 'startRow') && ($k != 'endRow') && ($k != 'education'))
{
$vo = null;
}else{
if($isStr){
$vo .= "";
}
}
}
return $data;
} /**
* 着色
* @param $colorarr
* @param $data
* @return mixed
*/
public static function color2data($colorarr,$data){
$count = count($colorarr);
$count_data = count($data);
$d = intval($count_data/$count);
$d = $d <= 1 ? 1 : $d;
$c = 0;
$n = 1;
foreach($data as &$vo)
{
$temp['style'] = 'esriSFSSolid';
$temp['color'] = $colorarr[$c];
$outline['color'] = array(106, 212, 238,255);
$outline['width'] = 1;
$temp['outline'] = $outline;
$vo['coverStyle'] =$temp;
if($n == $d)
{
if($c < $count-1)
{
$c++;
}
$n = 1;
}
else
{
$n++;
}
}
return $data;
} /**
* 截取字符串
* @param $str
* @param $start
* @param $lenth
* @return string
*/
public static function subStr($str, $start, $lenth)
{
$str1 = mb_substr($str,$start,$lenth,'UTF8');
return $str==$str1 ? $str : $str1.'...';
} /**
* 截取字符串
* @param $str
* @return int
*/
public static function str2num($str)
{
$num1 = (int)$str;
if($num1 == $str)
{ return $num1;
}
else
{
return $str;
} } /**
* 字符串转数组转字符串
* @param $data
* @return mixed
*/
public static function str2arr2str($data){
foreach($data as &$vo){
foreach($vo as &$vo1){
if(is_array($vo1))
{
$vo1 = json_encode($vo1);
// $vo1 = implode(',',$vo1);
}
}
}
return $data;
} public static function letter($value)
{
$letter = '';
do {
$letter = chr(65 + ($value % 26)) . $letter;
$temp = intval($value / 26);
if ($temp > 0) {
$value = $value - 26;
}
$value = intval($value / 26);
} while ($temp != 0);
return $letter;
} /**
* 调试函数
* @param unknown $str 要叠加字符的变量名
* @param unknown $addstr 要添加的字符
* @param string $ifdel 是否将之前的变量清空
* @return string
*/
public static function halt($logFile,$str,$ifdel=false)
{
header("Content-type: text/html; charset=utf-8");
$logname =LOG_PATH. $logFile . '-' . date("Ymdhis") . '.html';
$tmpstr = date("Y-m-d h:i:sa") . ' '; if ($ifdel) {
//清除日志文件内容
@file_put_contents($logname, "");
}
if (!empty($str)) {
$tmpstr .= '--' . $str;
}
try {
//将日导写入日导文件
self::writeFile($logname, $tmpstr . "\r\n", 'a+');
} catch (Exception $e) {
echo '写入日志出现错误!,错误内容为:' . $e->getMessage();
//$this->writeFile($logname,$str.'Error:'.$e);
}
} /**
* 写文件
* @param string $file 文件路径
* @param string $str 写入内容
* @param char $mode 写入模式
*/
public static function writeFile($file,$str,$mode='w')
{
$oldmask = @umask(0);
$fp = @fopen($file,$mode);
@flock($fp, 3);
if(!$fp)
{
Return false;
}
else
{
@fwrite($fp,$str);
@fclose($fp);
@umask($oldmask);
Return true;
}
} /**
* gbk 转 utf8
* @param $str
* @return string
*/
public static function utf8_to_gbk($str){
return mb_convert_encoding($str,'GBK','UTF-8');
} /**
* utf8 转 gbk
* @param $str
* @return string
*/
public static function gbk_to_utf8($str){
return mb_convert_encoding($str, 'UTF-8', 'GBK');
} /**
* utf8 转 gbk
* @param $str
* @return string
*/
public static function utf8_to_gb18030($str){
return mb_convert_encoding($str, 'GB18030','UTF-8');
}
public static function gb18030_to_utf8($str){
return mb_convert_encoding($str,'UTF-8', 'GB18030');
} public static function path_info($filepath,$ds='/')
{
$path_parts = array();
$path_parts ['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath,$ds)),$ds).$ds;
$path_parts ['basename'] = ltrim(substr($filepath, strrpos($filepath, $ds)),$ds);
$path_parts ['extension'] = substr(strrchr($filepath, '.'), 1);
$path_parts ['filename'] = ltrim(substr($path_parts ['basename'], 0, strrpos($path_parts ['basename'], '.')),$ds);
return $path_parts;
} /**
* 字符转码
* @param $str 字符
* @param string $Code 目标编码 "ASCII","UTF-8","GB2312","GBK","BIG5"
* @return mixed|string
*/
public static function convertCode($str,$Code="GB2312"){
$fromCode = mb_detect_encoding($str, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
// return mb_convert_encoding($str,$Code,$encode);
return iconv($fromCode,$Code."//IGNORE",$str);
}
public static function array_iconv($arr,$out_charset="GB2312"){
$fromCode = mb_detect_encoding(serialize($arr), array("ASCII","UTF-8","GB2312","GBK","BIG5"));
return eval('return '.\mb_convert_encoding(var_export($arr,true).';',$out_charset,$fromCode));
} /**
* 是否为windows操作系统,
* @return bool true:windows,false:其它操作系统
*/
public static function isWinOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') return true;
else return false;
}
/**
* 获取当前操作系统
* @return string
*/
public static function getOS(){
$os='';
$Agent=$_SERVER['HTTP_USER_AGENT'];
if (eregi('win',$Agent)&&strpos($Agent, '95')){
$os='Windows 95';
}elseif(eregi('win 9x',$Agent)&&strpos($Agent, '4.90')){
$os='Windows ME';
}elseif(eregi('win',$Agent)&&ereg('98',$Agent)){
$os='Windows 98';
}elseif(eregi('win',$Agent)&&eregi('nt 5.0',$Agent)){
$os='Windows 2000';
}elseif(eregi('win',$Agent)&&eregi('nt 6.0',$Agent)){
$os='Windows Vista';
}elseif(eregi('win',$Agent)&&eregi('nt 6.1',$Agent)){
$os='Windows 7';
}elseif(eregi('win',$Agent)&&eregi('nt 5.1',$Agent)){
$os='Windows XP';
}elseif(eregi('win',$Agent)&&eregi('nt',$Agent)){
$os='Windows NT';
}elseif(eregi('win',$Agent)&&ereg('32',$Agent)){
$os='Windows 32';
}elseif(eregi('linux',$Agent)){
$os='Linux';
}elseif(eregi('unix',$Agent)){
$os='Unix';
}else if(eregi('sun',$Agent)&&eregi('os',$Agent)){
$os='SunOS';
}elseif(eregi('ibm',$Agent)&&eregi('os',$Agent)){
$os='IBM OS/2';
}elseif(eregi('Mac',$Agent)&&eregi('PC',$Agent)){
$os='Macintosh';
}elseif(eregi('PowerPC',$Agent)){
$os='PowerPC';
}elseif(eregi('AIX',$Agent)){
$os='AIX';
}elseif(eregi('HPUX',$Agent)){
$os='HPUX';
}elseif(eregi('NetBSD',$Agent)){
$os='NetBSD';
}elseif(eregi('BSD',$Agent)){
$os='BSD';
}elseif(ereg('OSF1',$Agent)){
$os='OSF1';
}elseif(ereg('IRIX',$Agent)){
$os='IRIX';
}elseif(eregi('FreeBSD',$Agent)){
$os='FreeBSD';
}elseif($os==''){
$os='Unknown';
}
return $os;
} /**
* 定时任务日志处理函数
* @param $TaskData 任务数据
* @param $status 状态值,取值为: 0:待执行 1:执行中 2:已执行 3:待删除 4:已删除 5:异常'
* @param $info 备注信息
* @return mixed
*/
public static function TaskLog($TaskData,$status,$info){
$data=array(
'timer_id'=>$TaskData['timer_id'],
'timer_event'=>$TaskData['timer_event'],
'status'=>$status,
'from_type'=>$TaskData['from_type'],
'from_id'=>$TaskData['from_id'],
'addtime'=>time(),
'remark'=>$info,
);
return Db::table(Tool::getPrefix('system').'timer_log')->insert($data);
} public function checkmobile($mobilephone) {
$mobilephone = trim($mobilephone);
if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[01236789]{1}[0-9]{8}$|18[01236789]{1}[0-9]{8}$/",$mobilephone)){
return $mobilephone;
} else {
return false;
}
} /**
* Data转xml数据
* @param $data array
* @return mixed string
*/
public static function data2xmlfunc($data){
$xml = new \SimpleXMLElement('<xml></xml>');
self::data2xml($xml, $data);
return $xml->asXML();
}
public static function data2xml($xml, $data, $item = 'item'){
foreach ($data as $key => $value) {
is_numeric($key) && ($key = $item);
if (is_array($value) || is_object($value)) {
$child = $xml->addChild($key);
self::data2xml($child, $value, $item);
} else {
if (is_numeric($value)) {
$child = $xml->addChild($key, $value);
} else {
$child = $xml->addChild($key);
$node = dom_import_simplexml($child);
$node->appendChild($node->ownerDocument->createCDATASection($value));
}
}
}
} /**
* 将xml字符串转xml数组
* @param $xmlString
*/
public static function getXmlArray($xmlString){
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
} /**
* 出现科学计数法,还原成字符串
* @param $num
* @return float|string
*/
public static function NumToStr($num) {
if (stripos($num, 'e') === false)
return $num;
$num = trim(preg_replace('/[=\'"]/', '', $num, 1), '"'); //出现科学计数法,还原成字符串
$result = "";
while ($num > 0) {
$v = $num - floor($num / 10) * 10;
$num = floor($num / 10);
$result = $v . $result;
}
return $result;
} /**
* unset 空数据
* @param string $data
* @return array
*/
public static function unset_null_arr($data=''){
foreach($data as $k=>$vo)
{
foreach($vo as $k2=>$vo2)
{
if($vo2){
$arr[$k2] = $vo2;
}
else
{
$arr[$k2] = null;
}
} $arr2[] = $arr; }
return $arr2;
} /**
* 获取excel日期
* @param string $date
* @return mixed|string
*/
public static function get_excel_date($date=''){
$date = str_replace("年","/",$date);
$date = str_replace("月","/",$date);
$date = str_replace("日","",$date);
return $date;
} public static function debug($str){
return Debug::dump($str);
} /**
* 返回经htmlspecialchars处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
public static function strip_html_special_chars($string) {
$encoding = 'utf-8';
if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
}
/**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
public static function string2array($data) {
$data = trim($data);
if($data == '') return array();
if(strpos($data, 'array')===0){
@eval("\$array = $data;");
}else{
if(strpos($data, '{\\')===0) $data = stripslashes($data);
$array=json_decode($data,true);
// if(strtolower(CHARSET)=='gbk'){
// $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
// }
}
return $array;
}
/**
* 将数组转换为字符串
*
* @param array $data 数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
public static function array2string($data, $isformdata = 1) {
if($data == '' || empty($data)) return ''; if($isformdata) $data = new_stripslashes($data);
if(strtolower(CHARSET)=='gbk'){
$data = mult_iconv("GBK", "UTF-8", $data);
}
if (version_compare(PHP_VERSION,'5.3.0','<')){
return addslashes(json_encode($data));
}else{
return addslashes(json_encode($data,JSON_FORCE_OBJECT));
}
} /**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param boolean $adv 是否进行高级模式获取(有可能被伪装)
* @return mixed
*/
public static function get_client_ip($type = 0,$adv=false) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if($adv){
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
} /**
* 二维数组去处重复项
* @param $arr 传入数组
* @param $key 判断的key值
* @return array
*/
public static function array_unset($arr,$key){ //$arr-> $key->
//建立一个目标数组
$res = array();
foreach ($arr as $value) {
//查看有没有重复项
if(isset($res[$value[$key]])){
//有:销毁
unset($value[$key]);
}
else{
$res[$value[$key]] = $value;
}
}
return $res;
} /**
* 调用自定义类方法
* @param unknown $name
* @param unknown $model 分组名称
* @return Ambigous <unknown>
*/
public static function MM($name,$model=''){
static $_api_model = array();
$modelStr = empty($model)?MODULE_NAME:$model;
$classname = '\\app\\'.$modelStr.'\\Model\\'.$name;
if(!isset($_api_model[$name])) $_api_model[$name] = new $classname();
return $_api_model[$name]; } public static function get_grogress($start,$end){ $start = str_replace(",","",$start);
$end = str_replace(",","",$end);
$r = intval( $start/($start+$end)*100);
return $r;
} /**
* 生成编码
* @param $id 主键
* @param $type 类型 ,取值:实验:experiment,实验系列:experimentCategory,实验模板:experimentImage
* @return string
*/
public static function generateCode($id,$type){
$date=date('Ymd');
$prefix='';
switch($type){
case 'experiment':
$prefix='SY';
break;
case 'experimentCategory':
$prefix='SYXL';
break;
case 'experimentImage':
$prefix='RQMB';
break;
case 'ClassManagement':
$prefix='C';
break;
}
$returnStr=$prefix.$date.$id;
return $returnStr;
} public static function formatFilePath($file){
return str_replace("\\","/",$file);
} /**
* 获取时间间隔
* @param $startTime 开始时间
* @param $endTime 结束时间
* @return String
*/
public static function getDurationTime($startTime,$endTime){
if(empty($startTime)){
return "";
}else{
$endTime=empty($endTime)?time():strtotime($endTime);
$durationTime=$endTime-strtotime($startTime);
return self::time2Units($durationTime);
}
}
/**
* 时间差计算
*
* @param Timestamp $time
* @return String Time Elapsed
* @author Shelley Shyan
* @copyright http://phparch.cn (Professional PHP Architecture)
*/
public static function time2Units($time)
{
$year = floor($time / 60 / 60 / 24 / 365);
$time -= $year * 60 * 60 * 24 * 365;
$month = floor($time / 60 / 60 / 24 / 30);
$time -= $month * 60 * 60 * 24 * 30;
$week = floor($time / 60 / 60 / 24 / 7);
$time -= $week * 60 * 60 * 24 * 7;
$day = floor($time / 60 / 60 / 24);
$time -= $day * 60 * 60 * 24;
$hour = floor($time / 60 / 60);
$time -= $hour * 60 * 60;
$minute = floor($time / 60);
$time -= $minute * 60;
$second = $time;
$elapse = ''; $unitArr = array('年' => 'year', '个月' => 'month', '周' => 'week', '天' => 'day',
'小时' => 'hour', '分钟' => 'minute', '秒' => 'second'
); foreach ($unitArr as $cn => $u) {
if ($$u > 0) {
$elapse = $$u . $cn;
break;
}
} return $elapse;
}
public static function getRandCode($codeNum=4){
$str = "0123456789";
$code='';
for ($i = 0; $i < $codeNum; $i++) {
$code .= $str{rand(0, strlen($str) - 1)};
}
return $code;
} }
<?php
namespace isslib\Util;
use think\Config;
use think\Db;
use think\Debug; /**
* 常用工具类
* User: xaxiong
* Date: 2016/12/19
* Time: 13:47
*/
class Tool{ /**
* 简单加密处理函数
* @param $data
* @return string
*/
public static function encodeData($data){
return urlencode(json_encode($data));
} /**
* 简单解密处理函数
* @param $data
* @return mixed
*/
public static function decodeData($data){
return json_decode(urldecode($data),true);
} /**
* 获取数据表前缀
* @param string $mprefix 取值为:'origial':原始表;'dest':业务表;'system':系统表,标准知识库模型;'common':公共表
* @param bool $isprefix true 需要前缀,false不需要前缀
* @return mixed|string
*/
public static function getPrefix($mprefix='',$isprefix=true){
if($isprefix)
return empty($mprefix)?Config::get('database.prefix'):Config::get('database.prefix').Config::get('database.mprefix')[$mprefix];
else
return empty($mprefix)?'':Config::get('database.mprefix')[$mprefix];
} /**
* 对excel里的日期进行格式转化
* @param $val 数据
* @param $format 格式
* @return string
*/
public static function GetExceDate($val,$format){
if(!empty($val)) {
$jd = \GregorianToJD(1, 1, 1970);
$date = \JDToGregorian($jd + intval($val) - 25569);
// list($month, $day, $year) = explode('/',$date);
if (!empty($format)) $date = date($format, strtotime($date));
return $date;
}else{
return null;
}
} /**
* 格式化数字
* @param $number 要格式化的数值
* @param $type 类型 normal,electric
* @param $type 单位后缀
*/
public static function numberFormat($number,$type='normal',$extUnit='')
{
/**
* @var array 数据格式化类型
*/
$FORMAT_TYPE=array(
'normal'=>array(
array(
'base'=>100000000,
'unit'=>'亿'
),
array(
'base'=>10000,
'unit'=>'万'
),
array(
'base'=>1000,
'unit'=>'千'
),
array(
'base'=>1,
'unit'=>''
)
),
'electric'=>array(
array(
'base'=>1000000000000,
'unit'=>'TW'
),
array(
'base'=>1000000000,
'unit'=>'GW'
),
array(
'base'=>1000000,
'unit'=>'MW'
),
array(
'base'=>1000,
'unit'=>'KW'
),
array(
'base'=>1,
'unit'=>'W'
)
)
); $FORMAT_TYPE_ITEM=$FORMAT_TYPE[$type];
//$keys=array_keys($FORMAT_TYPE_ITEM);
//var_dump($FORMAT_TYPE_ITEM[$keys[0]]);exit();
if(empty($number)){
$arr['value']= 0;
$arr['unit']='';
$arr['base']=1;
return $arr;
}
return self::getMaxUnit($number,$FORMAT_TYPE_ITEM,$extUnit); } /**
* 获取最大单位数据
* @param $number 数字
* @param $AllArr 数据类型配置
* @param string $extUnit 单位
* @param array $currArr 当前数据
* @return array
*/
public static function getMaxUnit($number,$AllArr,$extUnit='',$currArr=array()){
//if($index>count($desArr)) return $returnArr;
if(empty($currArr)){
$currArr=$AllArr[0];
}
$key=$currArr['base'];
$value=$currArr['unit']; $leaveNum=$number/$key;
$resdata=array();
//arrayStep::getInstance($AllArr)->setCurrent($key);
if($leaveNum > 0 && $leaveNum < 1){
//$nextArr=arrayStep::getInstance($AllArr)->getNext();
$nextArr=next($AllArr);//var_dump($nextArr);
$data=self::getMaxUnit($number,$AllArr,$extUnit,$nextArr);
if(!empty($data))return $data;
}else{
$resdata= array(
'value'=>number_format(round($leaveNum)),
'unit'=>$value.$extUnit,
'base'=>$key
);
//var_dump($resdata);
return $resdata;
exit();
}
} /**
* 无限级分类,直接获取节点树
* @param unknown $list 数据集合
* @param string $pk 主键字段
* @param string $pid 父节点id对应字段
* @param string $child 子节点id对应字段
* @param number $root 从第几级开始查询
* @return multitype:unknown
*/
public static function list_to_tree($list, $pk='id',$pid = 'pid',$child = 'child',$root=0) {
// 创建Tree
$tree = array();
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[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
//无限极分类返回列表行记录
/**
*
* @param unknown $cate_info_sort 返回的数据
* @param unknown $data 原始数据
* @param string $pk 表主键
* @param string $pid_name 表父字段id
* @param number $pid 开始的父字段id
* @param string $kk 分割线
*/
public static function cate_sort(&$cate_info_sort,$data,$pk='id',$pid_name="pid",$pid=0,$kk="|"){
foreach($data as $k=> $v){
if($v[$pid_name]==$pid){
foreach ($v as $ke=>$vl){
$cate_info_sort[$k][$ke] = $vl;
}
$cate_info_sort[$k]["kk"] = $kk;
$pos = strpos($kk, "--");
if($pos === false){
$cate_info_sort[$k]["sun"] = 0;
}else{
$cate_info_sort[$k]["sun"] = 1;
}
self::cate_sort($cate_info_sort,$data ,$pk,$pid_name,$v[$pk],"&nbsp;&nbsp;&nbsp;&nbsp;".$kk."--");
}
}
} /**
* GET调用接口获取返回值
* @param $url url地址
* @param array $header 请求头配置
* @return mixed
*/
public static function curlGET($url,$header=array()){ $_SESSION['issTcSession']['get'][$url]['url'] = $url;
$_SESSION['issTcSession']['get'][$url]['header'] = $header;
// echo $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
$starttime=microtime(true);
$temp = curl_exec($ch);
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($ch);
return $temp;
} /**
* POST调用接口获取返回值
* @param $url url地址
* @param string $data 参数
* @param array $header 请求头
* @return mixed
*/
public static function curlPOST($url,$data='',$header=array()){ $_SESSION['issTcSession']['post'][$url]['url'] = $url;
$_SESSION['issTcSession']['post'][$url]['data'] = $data;
$_SESSION['issTcSession']['post'][$url]['header'] = $header;
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 $starttime=microtime(true);
$tmpInfo = curl_exec($curl); // 执行操作
// if (curl_errno($curl)) {
// echo 'Errno'.curl_error($curl);
// }
$endtime=microtime(true);
$data="---------接口请求总时间:".($endtime-$starttime)."-----------------------\n本次接口地址为:$url\n\n\n\n";
$_SESSION['logdata'.$_GET['a']]=$data;
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
} /**
* json数据返回格式化
* @param $data 数据
* @param string $status 状态
* @param string $errorCode 错误代码
* @param string $message 消息
* @param null $total 数据条数
*/
public static function jsonReturn($data,$status='1',$errorCode='1',$message='',$total=null)
{ if($data)
{
$json['status'] = 1;
$json['errorCode'] = $errorCode;
$json['errorMsg'] = '请求成功';
if($total)
{
$json['total'] = $total;
}
else
{
$json['total'] = count($data);
}
$json['data'] = $data;
}
else
{
if($status != '1')
{
$json['status'] = $status;
$json['errorCode'] = $errorCode;
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
else
{
$json['status'] = '0';
$json['errorCode'] = '0';
$json['errorMsg'] =empty($message)? '请求失败':$message;
}
$json['total'] = '0';
$json['data'] = array();
}
header("Content-type: application/json");
echo json_encode($json); } /**
* 保留小数
* @param $number 数字
* @param int $num 几位小数
* @return float|int
*/
public static function decimal($number,$num=1){
$number = round($number,$num);
$number1 = intval($number);
$number2 = $number > $number1 ? $number : $number1;
return $number2; } /**
* 数组排序
* @param $arr 数组
* @param $keys key名
* @param string $type 排序类型 asc,desc
* @param int $is0
* @param int $isK
* @return array
*/
public static function arraySort($arr, $keys, $type = 'asc',$is0=0,$isK=0) {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v){
$keysvalue[$k] = $v[$keys];
}
$type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
reset($keysvalue);
foreach ($keysvalue as $k => $v) { if($isK == 1)
{
$new_array[$k] = $arr[$k];
}
else
{
$new_array[] = $arr[$k];
} }
if($is0 == 1)
{
foreach($new_array as $vo_is0)
{
if($vo_is0[$keys] > 0){
$new_array_s[] = $vo_is0;
}
}
return $new_array_s;
}
return $new_array;
} /**
* 判断是否 为空 给 后端数据转成null
* @param $data
* @param int $isStr 0表示不转字符串,1:表示传成字符串
* @return mixed
*/
public static function arrIsNull($data,$isStr=0)
{
foreach($data as $k=>&$vo)
{
if(empty($vo) && ($k != 'startRow') && ($k != 'endRow') && ($k != 'education'))
{
$vo = null;
}else{
if($isStr){
$vo .= "";
}
}
}
return $data;
} /**
* 着色
* @param $colorarr
* @param $data
* @return mixed
*/
public static function color2data($colorarr,$data){
$count = count($colorarr);
$count_data = count($data);
$d = intval($count_data/$count);
$d = $d <= 1 ? 1 : $d;
$c = 0;
$n = 1;
foreach($data as &$vo)
{
$temp['style'] = 'esriSFSSolid';
$temp['color'] = $colorarr[$c];
$outline['color'] = array(106, 212, 238,255);
$outline['width'] = 1;
$temp['outline'] = $outline;
$vo['coverStyle'] =$temp;
if($n == $d)
{
if($c < $count-1)
{
$c++;
}
$n = 1;
}
else
{
$n++;
}
}
return $data;
} /**
* 截取字符串
* @param $str
* @param $start
* @param $lenth
* @return string
*/
public static function subStr($str, $start, $lenth)
{
$str1 = mb_substr($str,$start,$lenth,'UTF8');
return $str==$str1 ? $str : $str1.'...';
} /**
* 截取字符串
* @param $str
* @return int
*/
public static function str2num($str)
{
$num1 = (int)$str;
if($num1 == $str)
{ return $num1;
}
else
{
return $str;
} } /**
* 字符串转数组转字符串
* @param $data
* @return mixed
*/
public static function str2arr2str($data){
foreach($data as &$vo){
foreach($vo as &$vo1){
if(is_array($vo1))
{
$vo1 = json_encode($vo1);
// $vo1 = implode(',',$vo1);
}
}
}
return $data;
} public static function letter($value)
{
$letter = '';
do {
$letter = chr(65 + ($value % 26)) . $letter;
$temp = intval($value / 26);
if ($temp > 0) {
$value = $value - 26;
}
$value = intval($value / 26);
} while ($temp != 0);
return $letter;
} /**
* 调试函数
* @param unknown $str 要叠加字符的变量名
* @param unknown $addstr 要添加的字符
* @param string $ifdel 是否将之前的变量清空
* @return string
*/
public static function halt($logFile,$str,$ifdel=false)
{
header("Content-type: text/html; charset=utf-8");
$logname =LOG_PATH. $logFile . '-' . date("Ymdhis") . '.html';
$tmpstr = date("Y-m-d h:i:sa") . ' '; if ($ifdel) {
//清除日志文件内容
@file_put_contents($logname, "");
}
if (!empty($str)) {
$tmpstr .= '--' . $str;
}
try {
//将日导写入日导文件
self::writeFile($logname, $tmpstr . "\r\n", 'a+');
} catch (Exception $e) {
echo '写入日志出现错误!,错误内容为:' . $e->getMessage();
//$this->writeFile($logname,$str.'Error:'.$e);
}
} /**
* 写文件
* @param string $file 文件路径
* @param string $str 写入内容
* @param char $mode 写入模式
*/
public static function writeFile($file,$str,$mode='w')
{
$oldmask = @umask(0);
$fp = @fopen($file,$mode);
@flock($fp, 3);
if(!$fp)
{
Return false;
}
else
{
@fwrite($fp,$str);
@fclose($fp);
@umask($oldmask);
Return true;
}
} /**
* gbk 转 utf8
* @param $str
* @return string
*/
public static function utf8_to_gbk($str){
return mb_convert_encoding($str,'GBK','UTF-8');
} /**
* utf8 转 gbk
* @param $str
* @return string
*/
public static function gbk_to_utf8($str){
return mb_convert_encoding($str, 'UTF-8', 'GBK');
} /**
* utf8 转 gbk
* @param $str
* @return string
*/
public static function utf8_to_gb18030($str){
return mb_convert_encoding($str, 'GB18030','UTF-8');
}
public static function gb18030_to_utf8($str){
return mb_convert_encoding($str,'UTF-8', 'GB18030');
} public static function path_info($filepath,$ds='/')
{
$path_parts = array();
$path_parts ['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath,$ds)),$ds).$ds;
$path_parts ['basename'] = ltrim(substr($filepath, strrpos($filepath, $ds)),$ds);
$path_parts ['extension'] = substr(strrchr($filepath, '.'), 1);
$path_parts ['filename'] = ltrim(substr($path_parts ['basename'], 0, strrpos($path_parts ['basename'], '.')),$ds);
return $path_parts;
} /**
* 字符转码
* @param $str 字符
* @param string $Code 目标编码 "ASCII","UTF-8","GB2312","GBK","BIG5"
* @return mixed|string
*/
public static function convertCode($str,$Code="GB2312"){
$fromCode = mb_detect_encoding($str, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
// return mb_convert_encoding($str,$Code,$encode);
return iconv($fromCode,$Code."//IGNORE",$str);
}
public static function array_iconv($arr,$out_charset="GB2312"){
$fromCode = mb_detect_encoding(serialize($arr), array("ASCII","UTF-8","GB2312","GBK","BIG5"));
return eval('return '.\mb_convert_encoding(var_export($arr,true).';',$out_charset,$fromCode));
} /**
* 是否为windows操作系统,
* @return bool true:windows,false:其它操作系统
*/
public static function isWinOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') return true;
else return false;
}
/**
* 获取当前操作系统
* @return string
*/
public static function getOS(){
$os='';
$Agent=$_SERVER['HTTP_USER_AGENT'];
if (eregi('win',$Agent)&&strpos($Agent, '95')){
$os='Windows 95';
}elseif(eregi('win 9x',$Agent)&&strpos($Agent, '4.90')){
$os='Windows ME';
}elseif(eregi('win',$Agent)&&ereg('98',$Agent)){
$os='Windows 98';
}elseif(eregi('win',$Agent)&&eregi('nt 5.0',$Agent)){
$os='Windows 2000';
}elseif(eregi('win',$Agent)&&eregi('nt 6.0',$Agent)){
$os='Windows Vista';
}elseif(eregi('win',$Agent)&&eregi('nt 6.1',$Agent)){
$os='Windows 7';
}elseif(eregi('win',$Agent)&&eregi('nt 5.1',$Agent)){
$os='Windows XP';
}elseif(eregi('win',$Agent)&&eregi('nt',$Agent)){
$os='Windows NT';
}elseif(eregi('win',$Agent)&&ereg('32',$Agent)){
$os='Windows 32';
}elseif(eregi('linux',$Agent)){
$os='Linux';
}elseif(eregi('unix',$Agent)){
$os='Unix';
}else if(eregi('sun',$Agent)&&eregi('os',$Agent)){
$os='SunOS';
}elseif(eregi('ibm',$Agent)&&eregi('os',$Agent)){
$os='IBM OS/2';
}elseif(eregi('Mac',$Agent)&&eregi('PC',$Agent)){
$os='Macintosh';
}elseif(eregi('PowerPC',$Agent)){
$os='PowerPC';
}elseif(eregi('AIX',$Agent)){
$os='AIX';
}elseif(eregi('HPUX',$Agent)){
$os='HPUX';
}elseif(eregi('NetBSD',$Agent)){
$os='NetBSD';
}elseif(eregi('BSD',$Agent)){
$os='BSD';
}elseif(ereg('OSF1',$Agent)){
$os='OSF1';
}elseif(ereg('IRIX',$Agent)){
$os='IRIX';
}elseif(eregi('FreeBSD',$Agent)){
$os='FreeBSD';
}elseif($os==''){
$os='Unknown';
}
return $os;
} /**
* 定时任务日志处理函数
* @param $TaskData 任务数据
* @param $status 状态值,取值为: 0:待执行 1:执行中 2:已执行 3:待删除 4:已删除 5:异常'
* @param $info 备注信息
* @return mixed
*/
public static function TaskLog($TaskData,$status,$info){
$data=array(
'timer_id'=>$TaskData['timer_id'],
'timer_event'=>$TaskData['timer_event'],
'status'=>$status,
'from_type'=>$TaskData['from_type'],
'from_id'=>$TaskData['from_id'],
'addtime'=>time(),
'remark'=>$info,
);
return Db::table(Tool::getPrefix('system').'timer_log')->insert($data);
} public function checkmobile($mobilephone) {
$mobilephone = trim($mobilephone);
if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[01236789]{1}[0-9]{8}$|18[01236789]{1}[0-9]{8}$/",$mobilephone)){
return $mobilephone;
} else {
return false;
}
} /**
* Data转xml数据
* @param $data array
* @return mixed string
*/
public static function data2xmlfunc($data){
$xml = new \SimpleXMLElement('<xml></xml>');
self::data2xml($xml, $data);
return $xml->asXML();
}
public static function data2xml($xml, $data, $item = 'item'){
foreach ($data as $key => $value) {
is_numeric($key) && ($key = $item);
if (is_array($value) || is_object($value)) {
$child = $xml->addChild($key);
self::data2xml($child, $value, $item);
} else {
if (is_numeric($value)) {
$child = $xml->addChild($key, $value);
} else {
$child = $xml->addChild($key);
$node = dom_import_simplexml($child);
$node->appendChild($node->ownerDocument->createCDATASection($value));
}
}
}
} /**
* 将xml字符串转xml数组
* @param $xmlString
*/
public static function getXmlArray($xmlString){
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
} /**
* 出现科学计数法,还原成字符串
* @param $num
* @return float|string
*/
public static function NumToStr($num) {
if (stripos($num, 'e') === false)
return $num;
$num = trim(preg_replace('/[=\'"]/', '', $num, 1), '"'); //出现科学计数法,还原成字符串
$result = "";
while ($num > 0) {
$v = $num - floor($num / 10) * 10;
$num = floor($num / 10);
$result = $v . $result;
}
return $result;
} /**
* unset 空数据
* @param string $data
* @return array
*/
public static function unset_null_arr($data=''){
foreach($data as $k=>$vo)
{
foreach($vo as $k2=>$vo2)
{
if($vo2){
$arr[$k2] = $vo2;
}
else
{
$arr[$k2] = null;
}
} $arr2[] = $arr; }
return $arr2;
} /**
* 获取excel日期
* @param string $date
* @return mixed|string
*/
public static function get_excel_date($date=''){
$date = str_replace("年","/",$date);
$date = str_replace("月","/",$date);
$date = str_replace("日","",$date);
return $date;
} public static function debug($str){
return Debug::dump($str);
} /**
* 返回经htmlspecialchars处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
public static function strip_html_special_chars($string) {
$encoding = 'utf-8';
if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
}
/**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
public static function string2array($data) {
$data = trim($data);
if($data == '') return array();
if(strpos($data, 'array')===0){
@eval("\$array = $data;");
}else{
if(strpos($data, '{\\')===0) $data = stripslashes($data);
$array=json_decode($data,true);
// if(strtolower(CHARSET)=='gbk'){
// $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
// }
}
return $array;
}
/**
* 将数组转换为字符串
*
* @param array $data 数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
public static function array2string($data, $isformdata = 1) {
if($data == '' || empty($data)) return ''; if($isformdata) $data = new_stripslashes($data);
if(strtolower(CHARSET)=='gbk'){
$data = mult_iconv("GBK", "UTF-8", $data);
}
if (version_compare(PHP_VERSION,'5.3.0','<')){
return addslashes(json_encode($data));
}else{
return addslashes(json_encode($data,JSON_FORCE_OBJECT));
}
} /**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param boolean $adv 是否进行高级模式获取(有可能被伪装)
* @return mixed
*/
public static function get_client_ip($type = 0,$adv=false) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if($adv){
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
} /**
* 二维数组去处重复项
* @param $arr 传入数组
* @param $key 判断的key值
* @return array
*/
public static function array_unset($arr,$key){ //$arr-> $key->
//建立一个目标数组
$res = array();
foreach ($arr as $value) {
//查看有没有重复项
if(isset($res[$value[$key]])){
//有:销毁
unset($value[$key]);
}
else{
$res[$value[$key]] = $value;
}
}
return $res;
} /**
* 调用自定义类方法
* @param unknown $name
* @param unknown $model 分组名称
* @return Ambigous <unknown>
*/
public static function MM($name,$model=''){
static $_api_model = array();
$modelStr = empty($model)?MODULE_NAME:$model;
$classname = '\\app\\'.$modelStr.'\\Model\\'.$name;
if(!isset($_api_model[$name])) $_api_model[$name] = new $classname();
return $_api_model[$name]; } public static function get_grogress($start,$end){ $start = str_replace(",","",$start);
$end = str_replace(",","",$end);
$r = intval( $start/($start+$end)*100);
return $r;
} /**
* 生成编码
* @param $id 主键
* @param $type 类型 ,取值:实验:experiment,实验系列:experimentCategory,实验模板:experimentImage
* @return string
*/
public static function generateCode($id,$type){
$date=date('Ymd');
$prefix='';
switch($type){
case 'experiment':
$prefix='SY';
break;
case 'experimentCategory':
$prefix='SYXL';
break;
case 'experimentImage':
$prefix='RQMB';
break;
case 'ClassManagement':
$prefix='C';
break;
}
$returnStr=$prefix.$date.$id;
return $returnStr;
} public static function formatFilePath($file){
return str_replace("\\","/",$file);
} /**
* 获取时间间隔
* @param $startTime 开始时间
* @param $endTime 结束时间
* @return String
*/
public static function getDurationTime($startTime,$endTime){
if(empty($startTime)){
return "";
}else{
$endTime=empty($endTime)?time():strtotime($endTime);
$durationTime=$endTime-strtotime($startTime);
return self::time2Units($durationTime);
}
}
/**
* 时间差计算
*
* @param Timestamp $time
* @return String Time Elapsed
* @author Shelley Shyan
* @copyright http://phparch.cn (Professional PHP Architecture)
*/
public static function time2Units($time)
{
$year = floor($time / 60 / 60 / 24 / 365);
$time -= $year * 60 * 60 * 24 * 365;
$month = floor($time / 60 / 60 / 24 / 30);
$time -= $month * 60 * 60 * 24 * 30;
$week = floor($time / 60 / 60 / 24 / 7);
$time -= $week * 60 * 60 * 24 * 7;
$day = floor($time / 60 / 60 / 24);
$time -= $day * 60 * 60 * 24;
$hour = floor($time / 60 / 60);
$time -= $hour * 60 * 60;
$minute = floor($time / 60);
$time -= $minute * 60;
$second = $time;
$elapse = ''; $unitArr = array('年' => 'year', '个月' => 'month', '周' => 'week', '天' => 'day',
'小时' => 'hour', '分钟' => 'minute', '秒' => 'second'
); foreach ($unitArr as $cn => $u) {
if ($$u > 0) {
$elapse = $$u . $cn;
break;
}
} return $elapse;
}
public static function getRandCode($codeNum=4){
$str = "0123456789";
$code='';
for ($i = 0; $i < $codeNum; $i++) {
$code .= $str{rand(0, strlen($str) - 1)};
}
return $code;
} }

PHP常用工具类的更多相关文章

  1. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  2. IOS开发--常用工具类收集整理(Objective-C)(持续更新)

    前言:整理和收集了IOS项目开发常用的工具类,最后也给出了源码下载链接. 这些可复用的工具,一定会给你实际项目开发工作锦上添花,会给你带来大大的工作效率. 重复造轮子的事情,除却自我多练习编码之外,就 ...

  3. Apache Commons 常用工具类整理

    其实一直都在使用常用工具类,只是从没去整理过,今天空了把一些常用的整理一下吧 怎么使用的一看就明白,另外还有注释,最后的使用pom引入的jar包 public class ApacheCommonsT ...

  4. Android 常用工具类之SPUtil,可以修改默认sp文件的路径

    参考: 1. 利用Java反射机制改变SharedPreferences存储路径    Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import ...

  5. 封装一个简单好用的打印Log的工具类And快速开发系列 10个常用工具类

    快速开发系列 10个常用工具类 http://blog.csdn.net/lmj623565791/article/details/38965311 ------------------------- ...

  6. javaweb常用工具类及配置文件备份

    Javaweb常用工具类及配置文件备份   做一个代码备份,以后常用到的. hibernate工具类备份 package com.dly.service; /*  * hibernate获取sessi ...

  7. [C#] 常用工具类——直接在浏览器输出数据

    /// <summary> /// <para> </para> /// 常用工具类——直接在浏览器输出数据 /// <para> ---------- ...

  8. [C#] 常用工具类——加密解密类

    using System; using System.Configuration; using System.Collections.Generic; using System.Text; using ...

  9. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  10. [C#] 常用工具类——系统日志类

    using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespa ...

随机推荐

  1. python数据类型之列表类型

    一.列表 作用:多个装备,多个爱好,多门课程,多个女朋友等 定义:[]内可以有多个任意类型的值,逗号分隔 以下是列表的常用操作方法: append(), count(), insert(),rever ...

  2. PHP、mySQL及Navicat安装·Mac

    PHP配置 Mac系统对开发人员非常友好,除了自带Apache外,还带有能与Apache相匹配的服务器端脚本语言PHP,因此,Mac中PHP的启动只需要在Apache服务中进行一下超级简单的配置即可直 ...

  3. asp.net导入后台代码

    public void Upload(string information){ int Bank = 0; for (int i = 0; i <Request.Files.Count; i++ ...

  4. 不支持iframe框架?出来吧pdf

    <iframe src='http://km.shengaitcm.com/ADC/_layouts/15/WopiFrame.aspx?sourcedoc=%2FADC%2FDocLib6%2 ...

  5. Python练习:含参数的脚本示例

    首先准备一个example.csv文件,如下: 编写脚本test.py ,实现传入参数,读取example.csv文件,并将其保存为另一个文件, #  含参数的脚本,读取一个文件,并另保存一个文件im ...

  6. 网络库压力测试:mongols VS evpp

    evpp是360出品的一个网络库,基于libevent,进行了许多改造,对c++11友好.据称比libevent性能要好. 到底有多好呢?360开发人员有自己的测试,信不信由你. evpp源码下有个h ...

  7. 打造RecyclerView的n级列表

    先上效果图: 1.该多级列表的优势: 支持无限级列表展开 基于一个recyclerView实现 可以自定义每一级item的样式,定制化更强 2.设计的思路 数据结构List,ItemBean类中有变量 ...

  8. ES6 Promise用法讲解

    所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果. ES6 规定,Promise对象是一个构造函数,用来生成Promise实例. 下面代码创造了一个 ...

  9. CCF CSP 201709-1 打酱油 (贪心)

    题目链接:http://118.190.20.162/view.page?gpid=T63 问题描述 试题编号: 201709-1 试题名称: 打酱油 时间限制: 1.0s 内存限制: 256.0MB ...

  10. 标签EL和JSTL解读

    1. EL标签:出现代替输出:<%=%> EL输出格式(特点:只能输出,不带逻辑)  ${key值} 查找顺序:page,request,session,application **在不加 ...