在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
/**
* @desc 拼装wherein的条件
* @createTime 2017/06/28
* @author [email protected]
* @param array $paramArr
* @return string
*/
function getWhereIn($paramArr)
{
$whereIn = '(';
if (!empty($paramArr) && is_array($paramArr)) {
foreach ($paramArr as $val) {
$whereIn .= "'" . $val . "',";
}
}
$whereIn = rtrim($whereIn, ',');
$whereIn .= ')';
return $whereIn;
}
/**
* 获取uuid
* @return string
*/
function generateUUid()
{
$charId = md5(uniqid(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;
}
/**
* @desc 递归,将对象转成数组
* @author [email protected]
* @created time 2018-01-22
* @param object $stdclassobject
* @return array
*/
function std_class_object_to_array($stdclassobject)
{
$array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
foreach ($array as $key => $value) {
$value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
$array[$key] = $value;
}
return $array;
}
/**
* @desc 验证时间戳的有效性
* @author [email protected]
* @created time
* @param $timestamp
* @return bool
*/
function isValidTimeStamp($timestamp)
{
$timestamp = (string)$timestamp;
if (((string)(int)$timestamp === $timestamp) && (string)strtotime(date('Y-m-d H:i:s', $timestamp)) === $timestamp) {
return $timestamp;
} else return false;
}
/*
* 使用 PHP 正则表达式来匹配日期格式 Y-m-d
*/
function checkDateFormat($date)
{
//匹配日期格式
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
//检测是否为日期
if (checkdate($parts[2], $parts[3], $parts[1]))
return true;
else
return false;
} else
return false;
}
/**
* @desc 过滤数组或字符串 (主要是学习使用array_map这个函数)
* @created time 2017-11-2
* @author [email protected]
* @param string|array $value 被过滤的数据
* @return array|string
*/
function addslashesDeep($value)
{
if (!get_magic_quotes_gpc()) {
$value = is_array($value) ? array_map('addslashesDeep', $value) : addslashes($value);
}
return $value;
}
获取文件的大小,并且转换成便于阅读的KB,MB等格式。
function formatSize($size) {
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) {
return('n/a');
} else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
}
}
$thefile = filesize('test_file.mp3');
echo formatSize($thefile);
我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用...表示,以下函数可以满足你的需求
/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
if($code == 'UTF-8'){
$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $string, $t_string);
if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
return join('', array_slice($t_string[0], $start, $sublen));
}else{
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr = '';
for($i=0; $i<$strlen; $i++){
if($i>=$start && $i<($start+$sublen)){
if(ord(substr($string, $i, 1))>129){
$tmpstr.= substr($string, $i, 2);
}else{
$tmpstr.= substr($string, $i, 1);
}
}
if(ord(substr($string, $i, 1))>129) $i++;
}
if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
return $tmpstr;
}
}
$str = "jQuery插件实现的加载图片和页面效果";
echo cutStr($str,16);
跳转提示:
function message($msgTitle,$message,$jumpUrl){
$str = '<!DOCTYPE HTML>';
$str .= '<html>';
$str .= '<head>';
$str .= '<meta charset="utf-8">';
$str .= '<title>页面提示</title>';
$str .= '<style type="text/css">';
$str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial, sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';
$str .= '</style>';
$str .= '</head>';
$str .= '<body>';
$str .= '<div class="message">';
$str .= '<h3>'.$msgTitle.'</h3>';
$str .= '<div class="msg_txt">';
$str .= '<h4 class="red">'.$message.'</h4>';
$str .= '<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>';
$str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";
$str .= '</div>';
$str .= '</div>';
$str .= '</body>';
$str .= '</html>';
echo $str;
}
message('操作提示','操作成功!','http://www.helloweba.com/');
//遍历某个目录下的所有文件和子文件
function read_all_dir ( $dir )
{
$result = array();
$handle = opendir($dir);
if ( $handle )
{
while ( ( $file = readdir ( $handle ) ) !== false )
{
if ( $file != '.' && $file != '..')
{
$cur_path = $dir . DIRECTORY_SEPARATOR . $file;
if ( is_dir ( $cur_path ) )
{
$result['dir'][$cur_path] = read_all_dir ( $cur_path );
}
else
{
$result['file'][] = $cur_path;
}
}
}
closedir($handle);
}
return $result;
}
//获得网页中的所有链接
function getHrefUrl($weburl)
{
$str = file_get_contents($weburl);
$preg = '/<a .*?href="(.*?)".*?>/is';//用这个匹配的时候下面的$match[1]为所要结果
$preg = '/(http|ftp|https):\/\/([\w\d\-_]+[\.\w\d\-_]+)[:\d+]?([\/]?[\w\/\.\?=&;%@#\+,]+)/i';//用这个匹配时$match 结果数组索引0为全部结果、1为协议、2为域名、3为相对路径
preg_match_all($preg, $str, $match);//在$str中搜索匹配所有符合$preg加入$match中
/*for ($i = 0; $i < count($match[1]); $i++)//逐个输出超链接地址
{
echo $match[1][$i] . "<br />";
}*/
return $match;
}
编写一个php函数计算两个文件的相对路径
function getRelativePath($fileA, $fileB) {
$arrA = explode("/", $fileA);
$arrB = explode("/", $fileB);
array_pop($arrA);
array_pop($arrB);
$offset = 0;
foreach($arrB as $key => $value) {
if(!isset($arrA[$key]) || ($arrA[$key] != $arrB[$key])) {
$offset = $key;
break;
}
}
$relativePath = '';
for($i = $offset; $i <count($arrB); $i++) { $relativePath .= '../'; }
for($i=$offset; $i<count($arrA); $i++) { $relativePath .= $arrA[$i].'/'; }
return $relativePath;
}
/**
* 将秒数转换为时间(年、天、小时、分、秒)
* @param int $time 秒数比如86400
* @return bool|string
*/
public static function Sec2Time($time)
{
if (is_numeric($time)) {
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if ($time >= 31556926) {
$value["years"] = floor($time / 31556926);
$time = ($time % 31556926);
}
if ($time >= 86400) {
$value["days"] = floor($time / 86400);
$time = ($time % 86400);
}
if ($time >= 3600) {
$value["hours"] = floor($time / 3600);
$time = ($time % 3600);
}
if ($time >= 60) {
$value["minutes"] = floor($time / 60);
$time = ($time % 60);
}
$value["seconds"] = floor($time);
$t = $value["years"] . "年" . $value["days"] . "天" . " " . $value["hours"] . "小时" . $value["minutes"] . "分" . $value["seconds"] . "秒";
return $t;
} else {
return (bool)FALSE;
}
}
/**
* 初始化时间数组 形如['2017-06-13', '2017-06-12']
* @param string $beginDate 开始时间 Y-m-d H:i:s
* @param string $endDate 结束时间 Y-m-d H:i:s
* @param string $format 数组的时间格式
* @return array
*/
function initDate($beginDate, $endDate, $format = 'Y-m-d')
{
$beginDate = date('Y-m-d H:i:s', strtotime($beginDate));
$endDate = date('Y-m-d H:i:s', strtotime($endDate));
$datetime1 = new \DateTime($beginDate);
$datetime2 = new \DateTime($endDate);
$interval = $datetime1->diff($datetime2);
$dayCount = intval($interval->format('%a'));//$interval->format('%R%a days'); 会带正负
$date = [];
for($i = 0; $i< $dayCount; $i++) {
$date[$i] = date($format, strtotime($endDate. " -$i days"));
}
return $date;
}
/**
* 求两个时间差 $timediff = timediff( strtotime( "2011-10-28" ), strtotime( "2011-10-29" ));
* @param int $begin_time 时间戳格式
* @param int $end_time 时间戳格式
* @return array
*/
function timeDiff( $begin_time, $end_time )
{
if ( $begin_time < $end_time ) {
$starttime = $begin_time;
$endtime = $end_time;
} else {
$starttime = $end_time;
$endtime = $begin_time;
}
$timediff = $endtime - $starttime;
$days = intval( $timediff / 86400 );
$remain = $timediff % 86400;
$hours = intval( $remain / 3600 );
$remain = $remain % 3600;
$mins = intval( $remain / 60 );
$secs = $remain % 60;
$res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
return $res;
}
对二维数组中的第二维某一字段进行分组
public static function array_group_by($arr, $key)
{
$grouped = [];
foreach ($arr as $value) {
$grouped[$value[$key]][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$parms = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('array_group_by', $parms);
}
}
return $grouped;
}
/**
*当前日期是本月的第几周
* @param int $date Y-m-d格式的时间,下同
* @return int
* /
function weekOfMonth($date) {
$firstOfMonth = strtotime(date("Y-m-01", strtotime ($date)));
return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
}
//获取指定日期所在月的第一天和最后一天
function GetTheMonth($date)
{
$firstday = date("Y-m-01", strtotime($date));
$lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
return array($firstday, $lastday);
}
//PHP获得指定日期所在星期的第一天和最后一天
function getdays($date )
{
$lastday = date('Y-m-d', strtotime("$day Sunday"));
$firstday = date('Y-m-d', strtotime("$lastday -6 days"));
return array($firstday, $lastday);
}
/**
* 获得指定日期的前/后$step(正负表示指定日期所在月的前后的第几个月份)个月的第一天和最后一天日期
* @param $date
* @param $step
* @return string
*/
function AssignTabMonth($date, $step)
{
$date = date("Y-m-d", strtotime($step . " months", strtotime($date)));//得到处理后的日期(得到前后月份的日期)
$firstday = date("Y-m-01", strtotime($date));
$lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
return array($firstday, $lastday);
}
$date = date('Ymd', strtotime($date));
$lastday = date('Ymd', strtotime("$date Sunday"));//周日
$firstday = date('Ymd', strtotime("$lastday -6 days"));//周一
$firstday = date('Ymd', strtotime(date('Y-m-01', strtotime($date))));//指定日期所在月的第一天
$lastday = date("Ymd", strtotime("$firstday +1 month -1 day"));//指定日期所在月的最后一天
一对加密与解密方法
/*
* 加密方法
* @param string $input,待加密的字符串
* @param string $key,加密的密码(只能为8位长)
* @return string,加密之后的文本
* */
public static function encryptForDotNet($input, $key) {
$iv = $key;
$addnum = 8 - ( strlen($input) % 8 );
for ($i = 0; $i < $addnum; $i++) {
$input .= chr($addnum);
}
$output = mcrypt_encrypt(MCRYPT_DES, $key, $input, MCRYPT_MODE_CBC, $iv);
return base64_encode($output);
}
/*
* 解密方法
* @param string $input,待解密的字符串
* @param string $key,解密的密码(只能为8位长)
* @return string,解密之后的文本
* */
public static function decryptForDotNet($input, $key) {
$iv = $key;
$output = base64_decode($input);
$output = mcrypt_decrypt(MCRYPT_DES, $key, $output, MCRYPT_MODE_CBC, $iv);
for ($i = 0; $i <= 8; $i++) {
$output = str_replace(chr($i), "", $output);
}
return $output;
}
//二分查找
function bin_sch($array, $low, $high, $k)
{
if ($low <= $high) {
$mid = intval(($low + $high) / 2);
if ($array[$mid] == $k) {
return $mid;
} elseif ($k < $array[$mid]) {
return bin_sch($array, $low, $mid - 1, $k);
} else {
return bin_sch($array, $mid + 1, $high, $k);
}
}
return -1;
}
//顺序查找(数组里查找某个元素)
function seq_sch($array, $n, $k)
{
$array[$n] = $k;
for ($i = 0; $i < $n; $i++) {
if ($array[$i] == $k) {
break;
}
}
if ($i < $n) {
return $i;
} else {
return -1;
}
}
//线性表的删除(数组中实现)
function delete_array_element($array, $i)
{
$len = count($array);
for ($j = $i; $j < $len; $j++) {
$array[$j] = $array[$j + 1];
}
array_pop($array);
return $array;
}
//冒泡排序(数组排序)
function bubble_sort($array)
{
$count = count($array);
if ($count <= 0) return false;
for ($i = 0; $i < $count; $i++) {
for ($j = $count - 1; $j > $i; $j--) {
if ($array[$j] < $array[$j - 1]) {
$tmp = $array[$j];
$array[$j] = $array[$j - 1];
$array[$j - 1] = $tmp;
}
}
}
return $array;
}
//快速排序(数组排序)
function quick_sort($array)
{
if (count($array) <= 1) return $array;
$key = $array[0];
$left_arr = array();
$right_arr = array();
for ($i = 1; $i < count($array); $i++) {
if ($array[$i] <= $key)
$left_arr[] = $array[$i];
else
$right_arr[] = $array[$i];
}
$left_arr = quick_sort($left_arr);
$right_arr = quick_sort($right_arr);
return array_merge($left_arr, array($key), $right_arr);
}
//获得文件属性 $file是文件路径如$_SERVER['SCRIPT_FILENAME'],$flag文件的某个属性
function getFileAttr($file, $flag)
{
if (!file_exists($file)) {
return false;
}
switch ($flag) {
case 'dir':
if (is_file($file))
return dirname($file);
return realpath($file);
break;
case 'name':
if (is_file($file))
return basename($file);
return '-';
break;
case 'size':
if (is_file($file))
return filesize($file);
return '-';
break;
case 'perms':
return substr(sprintf('%o', fileperms($file)), -4);;
break;
case 'owner':
return fileowner($file);
break;
case 'ownername':
$ownerInfo = posix_getpwuid(fileowner($file));
return isset($ownerInfo['name']) ? $ownerInfo['name'] : false;
break;
case 'groupname':
$ownerInfo = posix_getpwuid(filegroup($file));
return isset($ownerInfo['name']) ? $ownerInfo['name'] : false;
break;
case 'ctime':
return filectime($file);
break;
case 'mtime':
return filemtime($file);
break;
case 'atime':
return fileatime($file);
break;
case 'suffix':
if (is_file($file))
return substr($file, strrpos($file, '.') + 1);
return '-';
break;
default:
return false;
break;
}
}
/**
* 整理json格式字符串数据
* @param string $json json格式字符串数据
* @param bool|false $assoc
* @param int $depth
* @param int $options
* @return mixed
*/
public function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0)
{
$json = str_replace(array("\n", "\r"), "", $json);
$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)#", '', $json);
$json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/', '$1"$3":', $json);
$json = preg_replace('/(,)\s*}$/', '}', $json);
if (version_compare(phpversion(), '5.4.0', '>=')) {
$json = json_decode($json, $assoc, $depth, $options);
} elseif (version_compare(phpversion(), '5.3.0', '>=')) {
$json = json_decode($json, $assoc, $depth);
} else {
$json = json_decode($json, $assoc);
}
return $json;
}
/**
* 判断$strJson是否是一个有效的json格式字符串
* @param $strJson
* @return bool
*/
public function isValidJson($strJson)
{
json_decode($strJson);
return (json_last_error() === JSON_ERROR_NONE);
}
/**
* 去掉字符串中的斜线(单斜线和双斜线)
* @param string $string
* @return string
*/
public static function removeslashes($string = '')
{
$string = implode("", explode("\\", $string));
return stripslashes(trim($string));
}
//去除数组中的单斜线
function stripslashes_deep($value)
{
$value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
return $value;
}
//入库添加斜线 防sql注入
function add_slashes_recursive( $variable )
{
if ( is_string( $variable ) )
return addslashes( $variable ) ;
elseif ( is_array( $variable ) )
foreach( $variable as $i => $value )
$variable[ $i ] = add_slashes_recursive( $value ) ;
return $variable ;
}
//页面显示时去掉数据库中数据的斜线
function strip_slashes_recursive( $variable )
{
if ( is_string( $variable ) )
return stripslashes( $variable ) ;
if ( is_array( $variable ) )
foreach( $variable as $i => $value )
$variable[ $i ] = strip_slashes_recursive( $value ) ;
return $variable ;
}
数据库操作
/**
* 连接MYSQL函数,需要在连接的时候传递一个数组
* @param array $config
* @return resource
*/
function connect1 ($config){
//连接mysql
$link=@mysql_connect($config['host'],$config['username'],$config['password']) or die ('数据库连接失败<br/>ERROR '.mysql_errno().':'.mysql_error());
//设置字符集
mysql_set_charset($config['charset']);
//打开指定的数据库
mysql_select_db($config['dbName']) or die('指定的数据库打开失败');
return $link;
}
/**建议使用该函数
* 连接MYSQL函数,通过常量的形式来连接数据库
* 自定义配置文件,配置文件中自定义常量,包含需要使用的信息
* @return resource
*/
function connect2 (){
//连接mysql
$link=@mysql_connect(DB_HOST,DB_USER,DB_PWD) or die ('数据库连接失败<br/>ERROR '.mysql_errno().':'.mysql_error());
//设置字符集
mysql_set_charset(DB_CHARSET);
//打开指定的数据库
mysql_select_db(DB_DBNAME) or die('指定的数据库打开失败');
return $link;
}
/* array(
'username'=>'king',
'password'=>'123123',
'email'=>'[email protected]'
) */
/**
* 插入记录的操作
* @param array $array
* @param string $table
* @return boolean
*/
function insert($array,$table){
$keys=join(',',array_keys($array));
$values="'".join("','", array_values($array))."'";
$sql="insert {$table}({$keys}) VALUES ({$values})";
$res=mysql_query($sql);
if($res){
return mysql_insert_id();
}else{
return false;
}
}
/**
* MYSQL更新操作
* @param array $array
* @param string $table
* @param string $where
* @return number|boolean
*/
function update($array,$table,$where=null){
foreach ($array as $key=>$val){
$sets.=$key."='".$val."',";
}
$sets=rtrim($sets,','); //去掉SQL里的最后一个逗号
$where=$where==null?'':' WHERE '.$where;
$sql="UPDATE {$table} SET {$sets} {$where}";
$res=mysql_query($sql);
if ($res){
return mysql_affected_rows();
}else {
return false;
}
}
/**
* 删除记录的操作
* @param string $table
* @param string $where
* @return number|boolean
*/
function delete($table,$where=null){
$where=$where==null?'':' WHERE '.$where;
$sql="DELETE FROM {$table}{$where}";
$res=mysql_query($sql);
if ($res){
return mysql_affected_rows();
}else {
return false;
}
}
/**
* 查询一条记录
* @param string $sql
* @param string $result_type
* @return boolean
*/
function fetchOne($sql,$result_type=MYSQL_ASSOC){
$result=mysql_query($sql);
if ($result && mysql_num_rows($result)>0){
return mysql_fetch_array($result,$result_type);
}else {
return false;
}
}
/**
* 得到表中的所有记录
* @param string $sql
* @param string $result_type
* @return boolean
*/
function fetchAll($sql,$result_type=MYSQL_ASSOC){
$result=mysql_query($sql);
if ($result && mysql_num_rows($result)>0){
while ($row=mysql_fetch_array($result,$result_type)){
$rows[]=$row;
}
return $rows;
}else {
return false;
}
}
/**取得结果集中的记录的条数
* @param string $sql
* @return number|boolean
*/
function getTotalRows($sql){
$result=mysql_query($sql);
if($result){
return mysql_num_rows($result);
}else {
return false;
}
}
/**释放结果集
* @param resource $result
* @return boolean
*/
function freeResult($result){
return mysql_free_result($result);
}
/**断开MYSQL
* @param resource $link
* @return boolean
*/function close($link=null){
return mysql_close($link);
}
/**得到客户端的信息
* @return string
*/
function getClintInfo(){
return mysql_get_client_info();
}
/**得到MYSQL服务器端的信息
* @return string
*/
function getServerInfo($link=null){
return mysql_get_server_info($link);
}
/**得到主机的信息
* @return string
*/
function getHostInfo($link=null){
return mysql_get_host_info($link);
}
/**得到协议信息
* @return string
*/
function getProtoInfo($link=null){
return mysql_get_proto_info($link);
}
/**
* 根据数据中的某一字段排序
* @param array $array 原始数组
* @param $field 数组字段
* @param bool|false $desc
*/
public function sortArrByField(&$array, $field, $desc = true)
{
$fieldArr = array();
foreach ($array as $k => $v) {
$fieldArr[$k] = $v[$field];
}
$sort = $desc ? SORT_DESC : SORT_ASC ;
array_multisort($fieldArr, $sort, $array);
}
//获得数组中重复的数据
function fetchRepeatMemberInArray($array)
{
// 获取去掉重复数据的数组
$unique_arr = array_unique($array);
// 获取重复数据的数组
$repeat_arr = array_diff_assoc($array, $unique_arr);
return $repeat_arr;
}
//PHP实现双端队列
class Deque
{
public $queue = array();
/**(尾部)入队 **/
public function addLast($value)
{
return array_push($this->queue,$value);
}
/**(尾部)出队**/
public function removeLast()
{
return array_pop($this->queue);
}
/**(头部)入队**/
public function addFirst($value)
{
return array_unshift($this->queue,$value);
}
/**(头部)出队**/
public function removeFirst()
{
return array_shift($this->queue);
}
/**清空队列**/
public function makeEmpty()
{
unset($this->queue);
}
/**获取列头**/
public function getFirst()
{
return reset($this->queue);
}
/** 获取列尾 **/
public function getLast()
{
return end($this->queue);
}
/** 获取长度 **/
public function getLength()
{
return count($this->queue);
}
}
//将ip转成int型类型 可直接用ip2long这个函数
// 整体思路 第一段乘以256的三次方,第二段乘以256的平方,第三段乘以256......最后总和
function ipToInt($ip)
{
$iparr = explode('.', $ip);
$num = 0;
for ($i = 0; $i < count($iparr); $i++) {
$num += intval($iparr[$i]) * pow(256, count($iparr) - ($i + 1));
}
return $num;
}
/**
* 取字符串首字母(如果是中文则取汉字对应拼音的首字母)
* @param string $str
* @return string|null
*/
public function getFirstCharter($str)
{
if (empty($str)) return null;
$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;
}
/**
* 获得客户端ip
* @return string
*/
public function getUserHostAddress()
{
switch(true){
case ($ip=getenv("HTTP_X_FORWARDED_FOR")):
break;
case ($ip=getenv("HTTP_CLIENT_IP")):
break;
default:
$ip=getenv("REMOTE_ADDR")?getenv("REMOTE_ADDR"):'127.0.0.1';
}
if (strpos($ip, ', ')>0) {
$ips = explode(', ', $ip);
$ip = $ips[0];
}
return $ip;
}
|
2022-08-30
2022-11-06
2022-08-16
2022-08-18
2022-07-18
请发表评论