最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

php开发中常用的一些方法

XAMPP相关 中文小张 41浏览 0评论
数组处理

 

/** * 数组层级缩进转换 * @param array $array 源数组 * @param int   $pid * @param int   $level * @return array */function Array2level($array, $pid = 0, $level = 1){    static $list = [];    foreach ($array as $v) {        if ($v['pid'] == $pid) {            $v['level'] = $level;            $list[]     = $v;            Array2level($array, $v['id'], $level + 1);        }    }    return $list;}


/** * 把返回的数据集转换成Tree * @access public * @param array $list 要转换的数据集 * @param string $pid parent标记字段 * @param string $level level标记字段 * @return array */function list_to_tree($list, $pk='id', $pid = 'pid', $child = 'son', $root = 0, $is_count = false) {    // 创建Tree    $tree = [];    if(is_array($list)) {        // 创建基于主键的数组引用        $refer = [];        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];                    if($is_count==true) $parent['_count'] = count($parent[$child]);                }            }        }    }    return $tree;}


/** * 将数据格式化成树形结构 * @param array $items * @return array */function genTree($items,$pk='id',$pid = 'pid', $child = '_child') {    $tree = []; //格式化好的树    foreach ($items as $item)        if (isset($items[$item[$pid]]))            $items[$item[$pid]][$child][] = &$items[$item[$pk]];        else            $tree[] = &$items[$item[$pk]];    return $tree;}



/** * 多个数组的笛卡尔积 * * @param unknown_type $data */function combineDika() {    $data = func_get_args();    $data = current($data);    $cnt = count($data);    $result = array();    $arr1 = array_shift($data);    foreach($arr1 as $key=>$item)    {        $result[] = array($item);    }     foreach($data as $key=>$item)    {        $result = combineArray($result,$item);    }    return $result;}



/** * 两个数组的笛卡尔积 * @param  array $arr1 [description] * @param  array $arr2 [description] * @return [type] [description] * @date   2017-08-07 * @author 赵俊峰 <981248356@qq.com> */function combineArray($arr1 =[],$arr2=[]) {    $result = [];    foreach ($arr1 as $item1)    {        foreach ($arr2 as $item2)        {            $temp = $item1;            $temp[] = $item2;            $result[] = $temp;        }    }    return $result;}


/** * 将二维数组以元素的某个值作为键 并归类数组 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') ) * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') )) * @param $arr 数组 * @param $key 分组值的key * @return array */function group_same_key($arr,$key){    $new_arr = array();    foreach($arr as $k=>$v ){        $new_arr[$v[$key]][] = $v;    }    return $new_arr;}



/** * @param $arr * @param $key_name * @return array * 将数据库中查出的列表以指定的 id 作为数组的键名 */function convert_arr_key($arr, $key_name='id'){    $arr2 = [];    foreach($arr as $key => $val){        $arr2[$val[$key_name]] = $val;    }    return $arr2;}


/** * 数组 转 对象 * * @param array $arr 数组 * @return object */function array_to_object($arr) {    if (gettype($arr) != 'array') {        return;    }    foreach ($arr as $k => $v) {        if (gettype($v) == 'array' || getType($v) == 'object') {            $arr[$k] = (object)array_to_object($v);        }    }     return (object)$arr;}



/** * 对象 转 数组 * @param object $obj 对象 * @return array */function object_to_array($obj) {    $obj = (array)$obj;    foreach ($obj as $k => $v) {        if (gettype($v) == 'resource') {            return;        }        if (gettype($v) == 'object' || gettype($v) == 'array') {            $obj[$k] = (array)object_to_array($v);        }    }     return $obj;}



//将 xml数据转换为数组格式。function xml_to_array($xml){    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";    if(preg_match_all($reg, $xml, $matches)){        $count = count($matches[0]);        for($i = 0; $i < $count; $i++){            $subxml= $matches[2][$i];            $key = $matches[1][$i];            if(preg_match( $reg, $subxml )){                $arr[$key] = xml_to_array( $subxml );            }else{                $arr[$key] = $subxml;            }        }    }    return $arr;}



 /** * array_delete  删除数组中的某个值 * @param $array * @param $value * @return mixed */function array_delete($array, $value){    $key = array_search($value, $array);    if ($key !== false)        array_splice($array, $key, 1);    return $array;}



// 分析枚举类型配置值 格式 a:名称1,b:名称2function parse_config_attr($value, $type = null) {    switch ($type) {        default: //解析"1:1\r\n2:3"格式字符串为数组            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));            if (strpos($value,':')) {                $value  = array();                foreach ($array as $val) {                    list($k, $v) = explode(':', $val);                    $value[$k]   = $v;                }            } else {                $value = $array;            }            break;    }    return $value;}



//array_column()函数兼容低版本PHPif (!function_exists('array_column')) {    function array_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;    }}

/** * PHP二维数组去重的方法(保留各个键值的同时去除重复的项) * $arr->传入数组 * $key->判断的key值 */function array_unset_tt($arr,$key){         //建立一个目标数组      $res = array();            foreach ($arr as $value) {        //查看有没有重复项        if(isset($res[$value[$key]])){            unset($value[$key]);  //有:销毁          }else{            $res[$value[$key]] = $value;          }        }      return $res;}

 

 

时间处理

 

/** * @param $begin_time * @param $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;}


/** * @param $sTime * @param string $type * @param string $alt * @return false|string * 个性化时间 */function friendlyDate($sTime, $type = 'normal', $alt = 'false'){    if (!$sTime) {        return '';    }    //sTime=源时间,cTime=当前时间,dTime=时间差    $cTime = time();    $dTime = $cTime - $sTime;    $dDay  = intval(date("z", $cTime)) - intval(date("z", $sTime));    //$dDay     =   intval($dTime/3600/24);    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));    //normal:n秒前,n分钟前,n小时前,日期    if ($type == 'normal') {        if ($dTime < 60) {            if ($dTime < 10) {                return '刚刚'; //by yangjs            } else {                return intval(floor($dTime / 10) * 10) . "秒前";            }        } elseif ($dTime < 3600) {            return intval($dTime / 60) . "分钟前";            //今天的数据.年份相同.日期相同.        } elseif ($dYear == 0 && $dDay == 0) {            //return intval($dTime/3600)."小时前";            return '今天' . date('H:i', $sTime);        } elseif ($dYear == 0) {            return date("m月d日 H:i", $sTime);        } else {            return date("Y-m-d", $sTime);        }    } elseif ($type == 'mohu') {        if ($dTime < 60) {            return $dTime . "秒前";        } elseif ($dTime < 3600) {            return intval($dTime / 60) . "分钟前";        } elseif ($dTime >= 3600 && $dDay == 0) {            return intval($dTime / 3600) . "小时前";        } elseif ($dDay > 0 && $dDay <= 7) {            return intval($dDay) . "天前";        } elseif ($dDay > 7 && $dDay <= 30) {            return intval($dDay / 7) . '周前';        } elseif ($dDay > 30) {            return intval($dDay / 30) . '个月前';        }        //full: Y-m-d , H:i:s    } elseif ($type == 'full') {        return date("Y-m-d , H:i:s", $sTime);    } elseif ($type == 'ymd') {        return date("Y-m-d", $sTime);    } else {        if ($dTime < 60) {            return $dTime . "秒前";        } elseif ($dTime < 3600) {            return intval($dTime / 60) . "分钟前";        } elseif ($dTime >= 3600 && $dDay == 0) {            return intval($dTime / 3600) . "小时前";        } elseif ($dYear == 0) {            return date("Y-m-d H:i:s", $sTime);        } else {            return date("Y-m-d H:i:s", $sTime);        }    }}

/** * 判断是否是时间戳 * @param  string $timestamp [description] * @return boolean [description] * @date   2018-10-06 * @author 心云间、凝听 <981248356@qq.com> */function is_timestamp($timestamp =''){    if (!$timestamp) return false;    return $is_unixtime = ctype_digit($timestamp) && $timestamp <= 2147483647;}



/** * 时间戳格式化 * @param int $time * @return string 完整的时间显示 * @author huajie <banhuajie@163.com> */function time_format($time = NULL, $format = 'Y-m-d H:i') {    $time = $time === NULL ? time() : intval($time);    return date($format, $time);}


/** * [getUserAge 获取用户年龄] * @param string $birthday    生日时间  例如:1987年11月09日 ||  1987-11-09 * @param string $type        时间显示  说说: 0 1987-11-09  1 1987年11月09日 * @return [type]           [description] */ function getUserAge($birthday) {     $str = substr($birthday,0,4);               //出生日期    $year = date('Y',time());                   //本年     return $age = $year - $str;                 //个人年龄  }

 

//转换剩余时间格式function get_surplus_time($time = 0){    if (!$time) {        return false;    }    if ($time < 0) {        return '已结束';    } else {        if ($time < 60) {            return $time . '秒';        } else {            if ($time < 3600) {                return floor($time / 60) . '分钟';            } else {                if ($time < 86400) {                    return floor($time / 3600) . '小时';                } else {                    if ($time < 259200) {//3天内                        return floor($time / 86400) . '天';                    } else {                        return floor($time / 86400) . '天';                    }                }            }        }    }}

/** * 判断是否日期时间 * @return string */function check_date_time($str_time, $format="Y-m-d H:i:s") {    $unix_time = strtotime($str_time);    $check_date= date($format, $unix_time);    if ($check_date == $str_time) {        return true;    } else {        return false;    }}

/** * get_some_day  获取n天前0点的时间戳 * @param int $some n天 * @param null $day 当前时间 * @return int|null * @author:xjw129xjt(肖骏涛) xjt@ourstu.com */function get_some_day($some = 30, $day = null){    $time = $day ? $day : time();    $some_day = $time - 60 * 60 * 24 * $some;    $btime = date('Y-m-d' . ' 00:00:00', $some_day);    $some_day = strtotime($btime);    return $some_day;}

 

 

其它

 

//获取客户端操作系统
function getOS(){    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);    if(strpos($agent, 'windows')) {        $platform = 'windows';    } elseif(strpos($agent, 'macintosh')) {        $platform = 'mac';    } elseif(strpos($agent, 'ipod')) {        $platform = 'ipod';    } elseif(strpos($agent, 'ipad')) {        $platform = 'ipad';    } elseif(strpos($agent, 'iphone')) {        $platform = 'iphone';    } elseif (strpos($agent, 'android')) {        $platform = 'android';    } elseif(strpos($agent, 'unix')) {        $platform = 'unix';    } elseif(strpos($agent, 'linux')) {        $platform = 'linux';    } else {        $platform = 'other';    }    return $platform;}

/** * 判断是否为手机访问 * @return  boolean */function is_mobile() {    static $is_mobile;
    if (isset($is_mobile)) {        return $is_mobile;    }
    if (empty($_SERVER['HTTP_USER_AGENT'])) {        $is_mobile = false;    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false    ) {        $is_mobile = true;    } else {        $is_mobile = false;    }
    return $is_mobile;}
/** * 系统加密方法 * @param string $data 要加密的字符串 * @param string $key  加密密钥 * @param int $expire  过期时间 单位 秒 * @return string * @author */function think_encrypt($data, $key = '', $expire = 0) {    $key  = md5(empty($key) ? config("pwd_script") : $key);    $data = base64_encode($data);    $x    = 0;    $len  = strlen($data);    $l    = strlen($key);    $char = '';
    for ($i = 0; $i < $len; $i++) {        if ($x == $l) $x = 0;        $char .= substr($key, $x, 1);        $x++;    }
    $str = sprintf('%010d', $expire ? $expire + time():0);
    for ($i = 0; $i < $len; $i++) {        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);    }    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));}

/** * 系统解密方法 * @param  string $data 要解密的字符串 (必须是think_encrypt方法加密的字符串) * @param  string $key  加密密钥 * @return string * @author */function think_decrypt($data, $key = ''){    $key    = md5(empty($key) ? config("pwd_script") : $key);    $data   = str_replace(array('-','_'),array('+','/'),$data);    $mod4   = strlen($data) % 4;    if ($mod4) {        $data .= substr('====', $mod4);    }    $data   = base64_decode($data);    $expire = substr($data,0,10);    $data   = substr($data,10);
    if($expire > 0 && $expire < time()) {        return '';    }    $x      = 0;    $len    = strlen($data);    $l      = strlen($key);    $char   = $str = '';
    for ($i = 0; $i < $len; $i++) {        if ($x == $l) $x = 0;        $char .= substr($key, $x, 1);        $x++;    }
    for ($i = 0; $i < $len; $i++) {        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));        }else{            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));        }    }    return base64_decode($str);}


/** * 替换手机号码中间四位数字 * @param  [type] $str [description] * @return [type]      [description] */function hide_phone($str){    $resstr = substr_replace($str,'****',3,4);    return $resstr;}



/** * 格式化字节大小 * @param  number $size      字节数 * @param  string $delimiter 数字和单位分隔符 * @return string            格式化后的带单位的大小 */function format_bytes($size, $delimiter = '') {    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;    return round($size, 2) . $delimiter . $units[$i];}

/** * 下载远程文件 * @Author   jackhhy */function getFile($url, $save_dir = '', $filename = '', $type = 0) {    if (trim($url) == '') {        return false;    }    if (trim($save_dir) == '') {        $save_dir = './';    }    if (0 !== strrpos($save_dir, '/')) {        $save_dir.= '/';    }    //创建保存目录    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {        return false;    }    //获取远程文件所采用的方法    if ($type) {        $ch = curl_init();        $timeout = 5;        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);        $content = curl_exec($ch);        curl_close($ch);    } else {        ob_start();        readfile($url);        $content = ob_get_contents();        ob_end_clean();    }    $size = strlen($content);    //文件大小    $fp2 = @fopen($save_dir . $filename, 'a');    fwrite($fp2, $content);    fclose($fp2);    unset($content, $url);    return $save_dir . $filename;}

/** * 获取文章第一张图片做为缩略图 * @param $content * @return bool|string */private static function thumb($content){    $content = stripslashes($content);    if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {        $str = $matches[3][0];        $str = substr($str, 6);        if (preg_match('/upload/', $str)) {            return $str;        }    }    return '';

转载请注明:XAMPP中文组官网 » php开发中常用的一些方法