php项目开发中常用的助手函数

匆匆过客 提交于 2019-11-30 11:23:19

在日常开发中有很多小功能或者函数方法都是复用率极高的,整理成一个助手函数类。

<?php
/**
*助手函数类
*/
class Helper
{
    /**
    *密码加密
    */
    public static function encryptPassword($password)
    {
        return md5(md5(trim($password)));
    }
    /**
     * 获取随机字符串.
     * @param integer $length Length.
     * @return string
     */
    public static function genRandomString($length)
    {
        $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $repeatTime = $length / strlen($charset);
        $charset = str_repeat($charset, $repeatTime + 1);
        $charset = str_shuffle($charset);
        return substr($charset, 0, $length);
    }
    /**
    *反转定义的数组,与传入的数组比较,返回交集,用于字段校验
    */
    public static function arrayFilterKey($arr, $keys)
    {
        return array_intersect_key($arr, array_flip($keys));
    }
    /**
    *去除数组中的空值,或返回白名单允许的值
    */
    public static function arrayFilterEmpty($arr, $whiteList = array())
    {
        foreach ($arr as $index => $value) {
            if (empty($value) || !in_array($index, $whiteList)) {
                unset($arr[$index]);
            }
        }
        return $arr;
    }
    
    /**
     * 过滤数组中的空值(不是值为false的情况)
     * @param $arr
     * @return mixed
     */
    public static function filterEmptyValue($arr)
    {
        foreach ($arr as $key => $val) {
            if ((is_array($val) && empty($val)) || $val === '' || $val === null) {
                unset($arr[$key]);
            }
        }
        return $arr;
    }
    
    /**
     * 过滤字段中的特殊字符
     * @param string $fields
     * @return mixed
     */
    public static function filterSelectFields($fields)
    {
        $fields = str_replace('%', '\%', $fields);              // 转义%符
        //$fields = preg_replace("/[[:punct:]]/", '', $fields);   // 去除标点符号
        $fields = str_replace(' ', '', $fields);                // 过滤空格
        return $fields;
    }
    /**
     * 加密
     */
    public static function encrypt($content, $priKey)
    {
        ksort($content);
        $content = json_encode($content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $res = openssl_get_publickey($priKey);
        //把需要加密的内容,按128位拆开加密
        $result = '';
        for ($i = 0; $i < ((strlen($content) - strlen($content) % 117) / 117 + 1); $i++) {
            $data = substr($content, $i * 117, 117);
            openssl_public_encrypt($data, $encrypted, $res);
            $result .= $encrypted;
        }
        openssl_free_key($res);
        //用base64将二进制编码
        $result = base64_encode($result);
        return $result;
    }

    public static function arrayReplaceExists(array $base, array $other)
    {
        foreach ($other as $key => $value) {
            if (array_key_exists($key, $base)) {
                $base[$key] = $value;
            }
        }
        return $base;
    }

    /**
     * 对数组的每一个对象增加一组固定的key -val字段
     * @param $key
     * @param $val
     */
    public static function setFixKeyValInPerItem($arr, $key, $val)
    {
        if (!empty($arr)) {
            foreach ($arr as &$row) {
                $row[$key] = $val;
            }
        }

        return $arr;
    }

    /**
     * 按key清理字段
     * @param $arr
     * @param $key
     */
    public static function unsetKeyPerItem($arr, $key)
    {
        if (!empty($arr)) {
            foreach ($arr as &$row) {
                unset($row[$key]);
            }
        }

        return $arr;
    }

    /**
     * 把对象的某个列作为列表hash的Key
     * @param $arr
     * @param $key
     */
    public static function pickItemColumnAsKey($arr, $key, $unique = false)
    {
        $newArr = array();
        if (!empty($arr)) {
            foreach ($arr as $row) {
                if (isset($row[$key])) {
                    $newRow = $row;
                    $newKey = strval($row[$key]);
                    if (!isset($newArr[$newKey])) {
                        $newArr[$newKey] = array();
                    }

                    if ($unique) {
                        $newArr[$newKey] = $newRow;
                    } else {
                        $newArr[$newKey][] = $newRow;
                    }
                }
            }
        }

        return $newArr;
    }

    /**
     * 挑出column对象作为新数组
     * @param $arr
     * @param $key
     */
    public static function pickUpColumnItem($arr, $colName)
    {
        return array_column((array)$arr, $colName);
        $newArr = array();
        if (!empty($arr)) {
            foreach ($arr as $row) {
                if (isset($row[$colName])) {
                    $newArr[] = $row[$colName];
                }
            }
        }

        return $newArr;
    }

    /**
     * 挑出column对象,并以另一个字段作为Key, 返回新数组
     * @param $arr
     * @param $key
     */
    public static function pickUpColumnItemWithKey($arr, $keyColName, $colName)
    {
        return array_column((array)$arr, $colName, $keyColName);
        $newArr = array();
        if (!empty($arr)) {
            foreach ($arr as $row) {
                if (isset($row[$colName]) && isset($row[$keyColName])) {
                    $newArr[$row[$keyColName]] = $row[$colName];
                }
            }
        }

        return $newArr;
    }
    
     /**
     * 根据Limit多的一个判断是否还有更多,顺便清理最后一个对象
     * @param $arrList
     * @param $limit
     * @return int
     */
    public static function getHasMoreAndPop(&$arrList, $limit)
    {
        if ($limit <= 0) {
            return 0;//error
        }

        $hasMore = 0;
        while (count($arrList) > $limit) {
            array_pop($arrList);
            $hasMore = 1;
        }

        return $hasMore;
    }

    /** 处理无限级分类,返回带有层级关系的树形结构
     * @param array $data 数据数组
     * @param int $root 根节点的父级id
     * @param string $id id字段名
     * @param string $pid 父级id字段名
     * @param string $child 树形结构子级字段名
     * @return array $tree 树形结构数组
     */
    public static function getMultilevelTree(array $data, $root = 0, $id = 'id', $pid = 'pid', $child = 'child')
    {
        $tree = [];
        $temp = [];

        foreach ($data as $key => $val) {
            $temp[$val[$id]] = &$data[$key];
        }
        foreach ($data as $key => $val) {
            $parentId = $val[$pid];
            if ($root == $parentId) {
                $tree[] = &$data[$key];
            } else {
                if (isset($temp[$parentId])) {
                    $parent = &$temp[$parentId];
                    $parent[$child][] = &$data[$key];
                }
            }
        }
        return $tree;
    }
    
    /**
     * 从一组数据中获取某个字段值,放入一个数组中
     * @param array $data
     * @param string $field
     * @return array
     */
    public static function getFieldInArray(array $data, $field = 'id')
    {
        $list = [];
        foreach ($data as $val) {
            if (isset($val[$field])) {
                $list[] = $val[$field];
            }
        }
        return $list;
    }
    
    /**
     * 插入数据到数组指定位置.
     *
     * @param integer $offset
     * @param array $insertData
     * @param array $data
     *
     * @return array
     */
    public static function insertDataToArray($offset, array $data, array $insertData)
    {
        $prevData = array_slice($data, 0, $offset);
        $lastData = array_slice($data, $offset);
        $prevData = array_merge($prevData, $insertData);
        return array_merge($prevData, $lastData);
    }
    
    /**
     * Http GET
     * @param string $url
     * @param array|string|null $params
     * @param array $headers
     * @return bool|mixed
     */
    public static function httpGet($url, $params = null, array $headers = [])
    {
        if (is_string($params) || is_array($params)) {
            is_array($params) AND $params = http_build_query($params);
            $url = rtrim($url, '?');
            if (strpos($url, '?') !== false) {
                $url .= '&' . $params;
            } else {
                $url .= '?' . $params;
            }
        }

        $ch = curl_init();

        curl_setopt_array($ch, self::$curlOptions);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPGET, true);//HTTP GET
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // 设置超时
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $headers AND curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $ret = curl_exec($ch);

        if ($errno = curl_errno($ch)) {
            \Log::error('HttpGet failed', [$url, $headers, $errno, curl_error($ch)]);
            $ret = false;
        }

        curl_close($ch);
        return $ret;
    }
    
    /**
     * HTTP POST
     * @param string $url
     * @param array|string|null $params
     * @param array $headers
     * @return bool|mixed
     */
    public static function httpPost($url, $params = null, array $headers = [])
    {
        $ch = curl_init();

        curl_setopt_array($ch, self::$curlOptions);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);//HTTP POST

        if (is_string($params) || is_array($params)) {
            is_array($params) AND $params = http_build_query($params);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        $headers AND curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $ret = curl_exec($ch);

        if ($errno = curl_errno($ch)) {
            \Log::error('httpPost failed', [$url, $params, $headers, $errno, curl_error($ch)]);
            $ret = false;
        }

        curl_close($ch);
        return $ret;
    }
    
    /**
     * 分转化成2位小数的元.
     *
     * @param $money
     *
     * @return float
     */
    public static function fen2Yuan($money)
    {
        return number_format($money / 100, 2, '.', '');
    }
    
    /**
     * 返回唯一订单号
     */
    public static function uniqueOrderNum ()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $year = 2017;
        $orderSn = $yCode[intval(date('Y')) - $year] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }
    
    /**
     * 防xss过滤
     * creator: liming
     * @param $string
     * @param bool|False $low
     * @return mixed|string
     */
    public static function cleanXss(&$string, $low = False)
    {
        if (!is_array($string)) {
            $string = trim($string);
            $string = strip_tags($string);
            $string = htmlspecialchars($string);
            if ($low) {
                return $string;
            }
            $string = str_replace(array(
                '"',
                "'",
                "..",
                "../",
                "./",
                '/',
                "//",
                "<",
                ">"
            ), '', $string);
            $no = '/%0[0-8bcef]/';
            $string = preg_replace($no, '', $string);
            $no = '/%1[0-9a-f]/';
            $string = preg_replace($no, '', $string);
            $no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
            $string = preg_replace($no, '', $string);
            return $string;
        }
        $keys = array_keys($string);
        foreach ($keys as $key) {
            self::cleanXss($string [$key]);
        }
    }
    
    public static function toArray($object)
    {
        return json_decode(json_encode($object), true);
    }

    public static function getParams($key = '')
    {
        if ($key) {
            return $_GET[$key];
        }
        return $_GET;
    }
    
    public static function getQueryParams($key = '')
    {
        $res = $_GET[$key];
        if (empty($res)){
            $res = $_POST[$key];
        }

        return $res;
    }
    
    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;
    }
    
    /**
     * 获取自然周时间列表
     * @return array
     */
    public static function getWeekList()
    {
        $time = time();
        $retData = [];
        for ($i = 1; $i <= 7; $i++) {
            $d = date('Ymd', $time - 86400 * (date('N', $time) - $i));
            $retData [] = $d;
        }
        return $retData;
    }
    
     /**
     * 生成随机字符串
     *
     * @param number $length
     */
    public static function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i ++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 取得两个数组中值的比较情况
     * @param array $newIds
     * @param array $oldIds
     * @return array
     */
    public static function updateArrayDiff(array $newIds, array $oldIds)
    {
        $addIds = array_diff($newIds, $oldIds);      // 删除的id
        $deleteIds = array_diff($oldIds, $newIds);         // 新增的id
        $sameIds = array_intersect($newIds, $oldIds);   // 不变的id

        return ['delete' => $deleteIds, 'add' => $addIds, 'same' => $sameIds];
    }
    
    /**
     * 将数组中的数字值转换为整型
     * @param array $arr
     * @param array $keyArr 需要转换的字段
     * @return array
     */
    public static function arrayToInt(array $arr, $keyArr = [])
    {
        if (!empty($keyArr)) {
            foreach ($keyArr as $value) {
                !array_key_exists($value, $arr) ? : $arr[$value] = intval($arr[$value]);
            }
        } else {
            array_walk($arr, function (&$value) {
                $value = intval($value);
            });
        }
        return $arr;
    }
    
    /**
     * 数据分组
     * @param array $input
     * @param string $field
     * @param bool $multi
     * @return array
     */
    public static function groupBy(array $input, $field, $multi = true)
    {
        $ret = [];
        foreach ($input as $k => $v) {
            if(!is_array($v)){
                $v=(array)$v;
            }
            $fieldVal = $v[$field];
            unset($v[$field]);
            if ($multi) {
                $ret[$fieldVal][] = $v;
            } else {
                $ret[$fieldVal] = $v;
            }
        }
        return $ret;
    }
    
    //按指定长度截断字符串,可选择补... 和尾部
    public static function breakLongString($input,$length=0,$ellipsis=false,$tail=""){
        $len=mb_strlen($input);
        if($len>$length){
            $new = mb_substr($input,0,$length);
            $ellipsis and $new=$new."...".$tail;
        }else{
            $new=$input;
        }

        return $new;
    }
    
    public static function hash256($data)
    {
        return hash("sha256", $data);
    }
    //根据时间戳生成唯一码
    public static function getUniqueCode($str=''){
        $time= microtime();
        $m=substr($time,10);
        $m=$m-1516188781;
        $um= substr($time,0,10)*1000000;
        $code= $str.'_'.base_convert(str_replace('.', '', $m), 10, 36).base_convert(str_replace('.', '', $um), 10, 36);
        return $code;

        //return base_convert(str_replace('.', '', $_SERVER['REQUEST_TIME_FLOAT']), 10, 36);
    }
    
    /**
     * 根据生日计算年龄
     * @param int $birthday 生日时间 yyyymmdd
     * @return int
     */
    public static function getAgeByBirthday($birthday)
    {
        if ($birthday == null) {
            return 0;
        }
        list($year, $month, $day) = explode('-', date('Y-m-d'));
        list($bYear, $bMonth, $bDay) = explode('-', date('Y-m-d', strtotime($birthday)));

        $age = $year - $bYear;

        if ($month < $bMonth) {
            --$age;
        }
        if ($month == $bMonth && $day < $bDay) {
            --$age;
        }

        $age <= 0 AND $age = 0;

        return $age;
    }
    
    /*
     * 检测是否是url
     * @param string $url
     * @return bool
     */
    public static function checkUrl ($url)
    {
        $pattern = "/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/";
        if (!preg_match($pattern, $url)){
            return false;
        }
        return true;
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!