各种函数方法

<?php

/**
 * 公共函数
 */

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

function encrypt($str) {
    return md5(C("AUTH_CODE") . $str);
}

/**
 * 获取数组中的某一列
 * @param type $arr 数组
 * @param type $key_name  列名
 * @return type  返回那一列的数组
 */
function get_arr_column($arr, $key_name) {
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[] = $val[$key_name];
    }
    return $arr2;
}

/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str) {
    $data = array();
    $str = explode('?', $str);
    $str = end($str);
    $parameter = explode('&', $str);
    foreach ($parameter as $val) {
        $tmp = explode('=', $val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}

/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc') {
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

/**
 * 多维数组转化为一维数组
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array) {
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time) {
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}

/**
 * 返回状态和信息
 * @param $status
 * @param $info
 * @return array
 */
function arrayRes($status, $info, $url = "") {
    return array("status" => $status, "info" => $info, "url" => $url);
}

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

// 服务器端IP
function serverIP() {
    return gethostbyname($_SERVER["SERVER_NAME"]);
}

/**
 * 自定义函数递归的复制带有多级子目录的目录
 * 递归复制文件夹
 * @param type $src 原目录
 * @param type $dst 复制到的目录
 */
//参数说明:            
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst) {
    $now = time();
    $dir = opendir($src);
    @mkdir($dst);
    while (false !== $file = readdir($dir)) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                recurse_copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
                    if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
                        exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
                    }
                    @unlink($dst . DIRECTORY_SEPARATOR . $file);
                }
                if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
                    @unlink($dst . DIRECTORY_SEPARATOR . $file);
                }
                $copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
                if (!$copyrt) {
                    echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed<br>';
                }
            }
        }
    }
    closedir($dir);
}

// 递归删除文件夹
function delFile($path, $delDir = FALSE) {
    if (!is_dir($path))
        return FALSE;
    $handle = @opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

/**
 * 多个数组的笛卡尔积
 *
 * @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 unknown_type $arr1
 * @param unknown_type $arr2
 */
function combineArray($arr1, $arr2) {
    $result = array();
    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 int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength = 6, $addtime = 1, $includenumber = 0) {
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}

/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method = "GET", $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2); /* 指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的 */
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /* curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        show_bug("=====post data======",'#000');
        show_bug($postfields);
        show_bug("=====info===== ",'#000');
        show_bug($requestinfo);
        show_bug("=====response=====",'#000');
        show_bug($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array) {
    if (!is_array($array))
        return trim($array);
    return array_map('trim_array_element', $array);
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile) {
    if (preg_match('/1[34578]\d{9}$/', $mobile))
        return true;
    return false;
}

/**
 * 检查固定电话
 * @param $mobile
 * @return bool
 */
function check_telephone($mobile) {
    if (preg_match('/^([0-9]{3,4}-)?[0-9]{7,8}$/', $mobile))
        return true;
    return false;
}

/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}

/**
 *   实现中文字串截取无乱码的方法
 */
function getSubstr($string, $start, $length) {
    if (mb_strlen($string, 'utf-8') > $length) {
        $str = mb_substr($string, $start, $length, 'utf-8');
        return $str . '...';
    } else {
        return $string;
    }
}

/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */

/**
    * 是否移动端访问访问
    *
    * @return bool
     */
function isMobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法,判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
    // 协议法,因为有可能不准确,放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } return false;
}

function is_qq() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
        return true;
    } return false;
}

function is_alipay() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return true;
    } return false;
}

//php获取中文字符拼音首字母
function getFirstCharter($str) {
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str[0]);
    if ($fchar >= ord('A') && $fchar <= ord('z'))
        return strtoupper($str[0]);
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s[0]) * 256 + ord($s[0]) - 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;
}

/**
 * 获取整条字符串汉字拼音首字母
 * @param $zh
 * @return string
 */
function pinyin_long($zh) {
    $ret = "";
    $s1 = iconv("UTF-8", "gb2312", $zh);
    $s2 = iconv("gb2312", "UTF-8", $s1);
    if ($s2 == $zh) {
        $zh = $s1;
    }
    for ($i = 0; $i < strlen($zh); $i++) {
        $s1 = substr($zh, $i, 1);
        $p = ord($s1);
        if ($p > 160) {
            $s2 = substr($zh, $i++, 2);
            $ret .= getFirstCharter($s2);
        } else {
            $ret .= $s1;
        }
    }
    return $ret;
}

function ajaxReturn($data) {
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($data));
}

function flash_sale_time_space() {
    $now_day = date('Y-m-d');
    $now_time = date('H');
    if ($now_time % 2 == 0) {
        $flash_now_time = $now_time;
    } else {
        $flash_now_time = $now_time - 1;
    }
    $flash_sale_time = strtotime($now_day . " " . $flash_now_time . ":00:00");
    $space = 7200;
    $time_space = array(
        '1' => array('font' => date("H:i", $flash_sale_time), 'start_time' => $flash_sale_time, 'end_time' => $flash_sale_time + $space),
        '2' => array('font' => date("H:i", $flash_sale_time + $space), 'start_time' => $flash_sale_time + $space, 'end_time' => $flash_sale_time + 2 * $space),
        '3' => array('font' => date("H:i", $flash_sale_time + 2 * $space), 'start_time' => $flash_sale_time + 2 * $space, 'end_time' => $flash_sale_time + 3 * $space),
        '4' => array('font' => date("H:i", $flash_sale_time + 3 * $space), 'start_time' => $flash_sale_time + 3 * $space, 'end_time' => $flash_sale_time + 4 * $space),
        '5' => array('font' => date("H:i", $flash_sale_time + 4 * $space), 'start_time' => $flash_sale_time + 4 * $space, 'end_time' => $flash_sale_time + 5 * $space),
    );
    return $time_space;
}

/**
 * 验证码操作(不生成图片)
 * @param array $inconfig  配置
 * @param sring $id 要生成验证码的标识 
 * @param string $incode 验证码,若为null生成验证码,否则检验验证码
 */
function capache($inconfig = [], $id = '', $incode = null) {
    $config = array(
        'seKey' => 'ThinkPHP.CN', // 验证码加密密钥
        'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY', // 验证码字符集合
        'expire' => 1800, // 验证码过期时间(s)
        'useZh' => false, // 使用中文验证码 
        'zhSet' => '们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借', // 中文验证码字符串
        'length' => 4, // 验证码位数
        'reset' => true, // 验证成功后是否重置
    );
    $config = array_merge($config, $inconfig);
    $authcode = function ($str) use ($config) {
        $key = substr(md5($config['seKey']), 5, 8);
        $str = substr(md5($str), 8, 10);
        return md5($key . $str);
    };

    /* 生成验证码 */
    if ($incode === null) {
        for ($i = 0; $i < $config['length']; $i++) {
            $code[$i] = $config['codeSet'][mt_rand(0, strlen($config['codeSet']) - 1)];
        }
        // 保存验证码
        $code_str = implode('', $code);
        $key = $authcode($config['seKey']);
        $code = $authcode(strtoupper($code_str));
        $secode = array();
        $secode['verify_code'] = $code; // 把校验码保存到session
        $secode['verify_time'] = NOW_TIME;  // 验证码创建时间
        session($key . $id, $secode);
        return $code_str;
    }

    /* 检验验证码 */
    if (is_string($incode)) {
        $key = $authcode($config['seKey']) . $id;
        // 验证码不能为空
        $secode = session($key);
        if (empty($incode) || empty($secode)) {
            return false;
        }
        // session 过期
        if (NOW_TIME - $secode['verify_time'] > $config['expire']) {
            session($key, null);
            return false;
        }

        if ($authcode(strtoupper($incode)) == $secode['verify_code']) {
            $config['reset'] && session($key, null);
            return true;
        }
        return false;
    }

    return false;
}

function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

/**
 * 获取
 */
function w_get($str = '') {
    $get = explode('_', key($_GET));
    $ary = array();
    $num = (count($get) - 1) / 2;
    if ($num == 0) {
        $ary['page'] = $get[0];
    } else {
        for ($i = 0; $i < $num; $i++) {
            if ($i == 0) {
                $ary['page'] = $get[$i];
            }
            $ary[($get[($i * 2) + 1])] = $get[($i * 2) + 2];
        }
    }
    if (!empty($str)) {
        return $ary[$str];
    } else {
        return $ary;
    }
}

function func_str($str, $str2) {
    if (strstr($str, $str2)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 设置session时间
 * @param type $name
 * @param type $value
 * @param type $time
 * @return boolean
 */
function sessiond($name, $value = false, $time = 99999) {
    if ($value === false) {
        if (session($name . "_time") < time()) {
            return false;
        } else {
            return session($name);
        }
    } else {
        session($name, $value);
        $d = time() + $time;
        if ($value === null) {
            $d = null;
        }
        session($name . "_time", $d);
        return true;
    }
}

/**
 * 
 * @param type $content
 * @param type $spd #语速,取值0-15,默认为5中语速
 * @return type
 */
function speech_synthesis($content = '测试语音效果', $spd = 5) {
    define('DEMO_CURL_VERBOSE', false);

# 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
    $apiKey = "t5WnxveTQiXGMppVebKoecnY";
# 填写网页上申请的APP SECRET 如 $secretKey="94dc99566550d87f8fa8ece112xxxxx"
    $secretKey = "lrRtuLY2ekY6rrQxl2dGNp9Gsgp6A506";

# text 的内容为"欢迎使用百度语音合成"的urlencode,utf-8 编码
# 可以百度搜索"urlencode" 
    $text = $content;

    $text2 = iconv("UTF-8", "GBK", $text);
    //    echo "text length :" . mb_strlen($text2, "GBK") . "\n";
    # 发音人选择, 基础音库:0为度小美,1为度小宇,3为度逍遥,4为度丫丫,
    # 精品音库:5为度小娇,103为度米朵,106为度博文,110为度小童,111为度小萌,默认为度小美 
    $per = 5;
    #音调,取值0-15,默认为5中语调
    $pit = 5;
    #音量,取值0-9,默认为5中音量
    $vol = 5;
    // 下载的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
    $aue = 3;

    $formats = array(3 => 'mp3', 4 => 'pcm', 5 => 'pcm', 6 => 'wav');
    $format = $formats[$aue];

    $cuid = "123456PHP";

    /** 公共模块获取token开始 */
    $auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" . $apiKey . "&client_secret=" . $secretKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $auth_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,0不验证
    curl_setopt($ch, CURLOPT_VERBOSE, DEMO_CURL_VERBOSE);
    $res = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);

//    echo "Token URL response is " . $res . "\n";
    $response = json_decode($res, true);

    if (!isset($response['access_token'])) {
//        echo "ERROR TO OBTAIN TOKEN\n";
        return array('status' => 2, 'data' => 'ERROR TO OBTAIN TOKEN');
    }
    if (!isset($response['scope'])) {
//        echo "ERROR TO OBTAIN scopes\n";
        return array('status' => 3, 'data' => 'ERROR TO OBTAIN OBTAIN');
    }

    if (!in_array('audio_tts_post', explode(" ", $response['scope']))) {
//        echo "DO NOT have tts permission\n";
        // 请至网页上应用内开通语音合成权限
        return array('status' => 3, 'data' => 'DO NOT have tts permission');
    }

    $token = $response['access_token'];
//    echo "token = $token ; expireInSeconds: ${response['expires_in']}\n\n";
    /** 公共模块获取token结束 */
    /** 拼接参数开始 * */
// tex=$text&lan=zh&ctp=1&cuid=$cuid&tok=$token&per=$per&spd=$spd&pit=$pit&vol=$vol
    $params = array(
        'tex' => urlencode($text), // 为避免+等特殊字符没有编码,此处需要2次urlencode。
        'per' => $per,
        'spd' => $spd,
        'pit' => $pit,
        'vol' => $vol,
        'aue' => $aue,
        'cuid' => $cuid,
        'tok' => $token,
        'lan' => 'zh', //固定参数
        'ctp' => 1, // 固定参数
    );
    $paramsStr = http_build_query($params);
    $url = 'http://tsn.baidu.com/text2audio';
    $urltest = $url . '?' . $paramsStr;
//    echo $urltest . "\n"; // 反馈请带上此url

    /** 拼接参数结束 * */
    $g_has_error = true;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsStr);

    function read_header($ch, $header) {
        global $g_has_error;

        $comps = explode(":", $header);
        // 正常返回的头部 Content-Type: audio/*
        // 有错误的如 Content-Type: application/json
        if (count($comps) >= 2) {
            if (strcasecmp(trim($comps[0]), "Content-Type") == 0) {
                if (strpos($comps[1], "audio/") > 0) {
                    $g_has_error = false;
                } else {
                    echo $header . " , has error \n";
                }
            }
        }
        return strlen($header);
    }

    curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo curl_error($ch);
        exit(2);
    }
    curl_close($ch);
    $file = $g_has_error ? "result.txt" : "result." . $format;
    file_put_contents($file, $data);
    return array('status' => 1, 'data' => $urltest . $file);
//    echo "\n$file saved successed, please open it \n";
}

function findNum($str = '') {
    $str = trim($str);
    if (empty($str)) {
        return '';
    }
    $reg = '/(\d{3}(\.\d+)?)/is'; //匹配数字的正则表达式
    preg_match_all($reg, $str, $result);
    if (is_array($result) && !empty($result) && !empty($result[1]) && !empty($result[1][0])) {
        return $result[1][0];
    }
    return '';
}

//制作一个输出调试函数
function show_bug($msg, $color = 'red') {
    echo "<pre style='color:" . $color . "'>";
    var_dump($msg);
    echo "</pre>";
}

很多方法

  1 <?php
  2 
  3 use think\Db;
  4 
  5 /**
  6  * @param
  7  * @return bool 2
  8  */
  9 function is_login() {
 10     if (isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0) {
 11         return $_SESSION['admin_id'];
 12     } else {
 13         return false;
 14     }
 15 }
 16 
 17 /**
 18  * 记录帐户变动
 19  * @param   int     $user_id        用户id
 20  * @param   float   $user_money     可用余额变动
 21  * @param   int     $pay_points     消费积分变动
 22  * @param   string  $desc    变动说明
 23  * @param   float   distribut_money 分佣金额
 24  * @param int $order_id 订单id
 25  * @param string $order_sn 订单sn
 26  * @return  bool
 27  */
 28 function accountLog($user_id, $user_money = 0, $desc = '', $distribut_money = 0, $order_id = 0) {
 29     /* 插入帐户变动记录 */
 30     $account_log = array(
 31         'user_id' => $user_id,
 32         'user_money' => $user_money,
 33         'change_time' => time(),
 34         'desc' => $desc,
 35         'order_id' => $order_id
 36     );
 37     $update_data = array(
 38         'user_money' => ['exp', 'user_money+' . $user_money],
 39         'distribut_money' => ['exp', 'distribut_money+' . $distribut_money],
 40     );
 41 //    $update = Db::name('users')->where('user_id', $user_id)->update($update_data);
 42     if ($update !== false) {
 43         M('account_log')->add($account_log);
 44         return true;
 45     } else {
 46         return false;
 47     }
 48 }
 49 
 50 /**
 51  * 写入静态页面缓存
 52  */
 53 function write_html_cache($html) {
 54     $html_cache_arr = C('HTML_CACHE_ARR');
 55     $request = think\Request::instance();
 56     $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
 57     $m_c_a_str = strtolower($m_c_a_str);
 58     //exit('write_html_cache写入缓存<br/>');
 59     if (is_array($html_cache_arr)) {
 60         foreach ($html_cache_arr as $key => $val) {
 61             $val['mca'] = strtolower($val['mca']);
 62             if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
 63                 continue;
 64 
 65             //if(!is_dir(RUNTIME_PATH.'html'))
 66             //mkdir(RUNTIME_PATH.'html');
 67             //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
 68             $filename = $m_c_a_str;
 69             // 组合参数  
 70             if (isset($val['p'])) {
 71                 foreach ($val['p'] as $k => $v)
 72                     $filename .= '_' . $_GET[$v];
 73             }
 74             $filename .= '.html';
 75             \think\Cache::set($filename, $html);
 76             //file_put_contents($filename, $html);
 77         }
 78     }
 79 }
 80 
 81 /**
 82  * 读取静态页面缓存
 83  */
 84 function read_html_cache() {
 85     $html_cache_arr = C('HTML_CACHE_ARR');
 86     $request = think\Request::instance();
 87     $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
 88     $m_c_a_str = strtolower($m_c_a_str);
 89     //exit('read_html_cache读取缓存<br/>');
 90     foreach ($html_cache_arr as $key => $val) {
 91         $val['mca'] = strtolower($val['mca']);
 92         if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
 93             continue;
 94 
 95         //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
 96         $filename = $m_c_a_str;
 97         // 组合参数        
 98         if (isset($val['p'])) {
 99             foreach ($val['p'] as $k => $v)
100                 $filename .= '_' . $_GET[$v];
101         }
102         $filename .= '.html';
103         $html = \think\Cache::get($filename);
104         if ($html) {
105             //echo file_get_contents($filename);
106             echo \think\Cache::get($filename);
107             exit();
108         }
109     }
110 }
111 
112 /**
113  * 获取缓存或者更新缓存
114  * @param string $config_key 缓存文件名称
115  * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
116  * @return array or string or bool
117  */
118 function tpCache($config_key, $data = array()) {
119     $param = explode('.', $config_key);
120     if (empty($data)) {
121         //如$config_key=shop_info则获取网站信息数组
122         //如$config_key=shop_info.logo则获取网站logo字符串
123         $config = F($param[0], '', TEMP_PATH); //直接获取缓存文件
124         if (empty($config)) {
125             //缓存文件不存在就读取数据库
126             $res = D('config')->where("inc_type", $param[0])->select();
127             if ($res) {
128                 foreach ($res as $k => $val) {
129                     $config[$val['name']] = $val['value'];
130                 }
131                 F($param[0], $config, TEMP_PATH);
132             }
133         }
134         if (count($param) > 1) {
135             return $config[$param[1]];
136         } else {
137             return $config;
138         }
139     } else {
140         //更新缓存
141         $result = D('config')->where("inc_type", $param[0])->select();
142         if ($result) {
143             foreach ($result as $val) {
144                 $temp[$val['name']] = $val['value'];
145             }
146             foreach ($data as $k => $v) {
147                 $newArr = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
148                 if (!isset($temp[$k])) {
149                     M('config')->add($newArr); //新key数据插入数据库
150                 } else {
151                     if ($v != $temp[$k])
152                         M('config')->where("name", $k)->save($newArr); //缓存key存在且值有变更新此项
153                 }
154             }
155             //更新后的数据库记录
156             $newRes = D('config')->where("inc_type", $param[0])->select();
157             foreach ($newRes as $rs) {
158                 $newData[$rs['name']] = $rs['value'];
159             }
160         } else {
161             foreach ($data as $k => $v) {
162                 $newArr[] = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
163             }
164             M('config')->insertAll($newArr);
165             $newData = $data;
166         }
167         return F($param[0], $newData, TEMP_PATH);
168     }
169 }
170 
171 /**
172  * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
173  * @param type $cat_id
174  */
175 function getCatGrandson($cat_id) {
176     $GLOBALS['catGrandson'] = array();
177     $GLOBALS['category_id_arr'] = array();
178     // 先把自己的id 保存起来
179     $GLOBALS['catGrandson'][] = $cat_id;
180     // 把整张表找出来
181     $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true, TPSHOP_CACHE_TIME)->getField('gct_id,parent_id');
182     // 先把所有儿子找出来
183     $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true, TPSHOP_CACHE_TIME)->getField('gct_id', true);
184     foreach ($son_id_arr as $k => $v) {
185         getCatGrandson2($v);
186     }
187     return $GLOBALS['catGrandson'];
188 }
189 
190 /**
191  * 递归调用找到 重子重孙
192  * @param type $cat_id
193  */
194 function getCatGrandson2($cat_id) {
195     $GLOBALS['catGrandson'][] = $cat_id;
196     foreach ($GLOBALS['category_id_arr'] as $k => $v) {
197         // 找到孙子
198         if ($v == $cat_id) {
199             getCatGrandson2($k); // 继续找孙子
200         }
201     }
202 }
203 
204 /**
205  * jqGrid 原生查询方法
206  * @param type $sql 算起来语句
207  * @param type $group 分组字段
208  * @return type array();
209  */
210 function JQGrid($sql, $group = '', $count_sql = '') {
211     $responce = new \stdClass();
212     //JQGrid数据
213     $page = $_GET['page']; // get the requested page
214     $limit = $_GET['rows']; // get how many rows we want to have into the grid
215     $sidx = $_GET['sidx']; // get index row - i.e. user click to sort
216     $sord = $_GET['sord']; // get the direction
217     $order = '';
218     if ($sidx != false) {
219         $order = " ORDER BY " . $sidx . " " . $sord;
220     }
221     //$sidx = 1;
222     if (!empty($group)) {
223         $sql .= " GROUP BY " . $group;
224     }
225     if (empty($count_sql)) {
226         $countinfo = DB::query($sql);
227         $count = count($countinfo);
228     } else {
229         $count = DB::query($count_sql)[0]["num"];
230     }
231     if ($count > 0) {
232         $total_pages = ceil($count / $limit);
233     } else {
234         $total_pages = 0;
235     }
236     if ($page > $total_pages)
237         $page = $total_pages;
238     $start = $limit * $page - $limit; // do not put $limit*($page - 1)
239     if ($start < 0) {
240         $start = 0;
241     }
242 
243     $sql .= $order . " LIMIT " . $start . "," . $limit;
244     $row = DB::query($sql);
245 //show_bug($sql);
246     $responce->page = $page;
247     $responce->total = $total_pages;
248     $responce->records = $count;
249     $responce->rows = $row;
250     return $responce;
251 }
252 
253 /**
254  * jqGrid tp查询方法
255  * @param type $sql 算起来语句
256  * @param type $group 分组字段
257  * @return type array();
258  */
259 function JQGrid_tp($sql_parm = array()) {
260     $responce = new \stdClass();
261     //JQGrid数据
262     $page = $_GET['page']; // get the requested page
263     $limit = $_GET['rows']; // get how many rows we want to have into the grid
264     $sidx = $_GET['sidx']; // get index row - i.e. user click to sort
265     $sord = $_GET['sord']; // get the direction
266     if (!empty($sql_parm['group'])) {
267         $sql_parm['mod'] = $sql_parm['mod']->GROUP($sql_parm['group']);
268     }
269     if (empty($sql_parm['count_sql'])) {
270         $ref_mod = (clone $sql_parm['mod']);
271         $count = $ref_mod->count();
272     } else {
273         $count = DB::query($sql_parm['count_sql'])[0]["num"];
274     }
275     if (!empty($sql_parm['field'])) {
276         $sql_parm['mod'] = $sql_parm['mod']->field($sql_parm['field']);
277     }
278     if ($sidx != false) {
279         $sql_parm['mod'] = $sql_parm['mod']->order($sidx . ' ' . $sord);
280     }
281     if ($count > 0) {
282         $total_pages = ceil($count / $limit);
283     } else {
284         $total_pages = 0;
285     }
286     if ($page > $total_pages)
287         $page = $total_pages;
288     $start = $limit * $page - $limit; // do not put $limit*($page - 1)
289     if ($start < 0) {
290         $start = 0;
291     }
292     $sql_parm['mod'] = $sql_parm['mod']->limit($start . "," . $limit);
293     $row = $sql_parm['mod']->select();
294 //show_bug($sql);
295     $responce->page = $page;
296     $responce->total = $total_pages;
297     $responce->records = $count;
298     $responce->rows = $row;
299     return $responce;
300 }
301 
302 /**
303  * jqGrid 数组处理
304  * @param type $arr
305  * @return type
306  */
307 function JQGrid_array($arr) {
308     $responce = new \stdClass();
309     $page = I('page'); // get the requested page
310     $limit = I('rows'); // get how many rows we want to have into the grid
311     $sidx = I('sidx'); // get index row - i.e. user click to sort
312     $sord = I('sord'); // get the direction
313     $count = count($arr);
314     if ($count > 0) {
315         $total_pages = ceil($count / $limit);
316     } else {
317         $total_pages = 0;
318     }
319     if ($page > $total_pages)
320         $page = $total_pages;
321     $start = $limit * $page - $limit; // do not put $limit*($page - 1)
322     if ($start < 0) {
323         $start = 0;
324     }
325 
326     //按下面字段排序
327     $score = array();
328     foreach ($arr as $k => $v) {
329         $score[$k] = $v[$sidx];
330     }
331     //按下面的方式(升序/降序)
332     $sordStr = '';
333     if ($sord == 'asc' || $sord == 'ASC') {
334         $sordStr = SORT_ASC;
335     } elseif ($sord == 'desc' || $sord == 'DESC') {
336         $sordStr = SORT_DESC;
337     }
338 
339     array_multisort($score, $sordStr, SORT_REGULAR, $arr);
340 
341     $row = array_slice($arr, $start, $limit);
342     $responce->page = $page;
343     $responce->total = $total_pages;
344     $responce->records = $count;
345     $responce->rows = $row;
346     return $responce;
347 }
348 
349 /**
350  * 检测是否能够发送短信
351  * @param unknown $scene
352  * @return multitype:number string
353  */
354 function checkEnableSendSms($scene) {
355 
356     $scenes = C('SEND_SCENE');
357     $sceneItem = $scenes[$scene];
358     if (!$sceneItem) {
359         return array("status" => -1, "msg" => "场景参数'scene'错误!");
360     }
361     $key = $sceneItem[2];
362     $sceneName = $sceneItem[0];
363     $config = tpCache('sms');
364     $smsEnable = $config[$key];
365 
366     if (!$smsEnable) {
367         return array("status" => -1, "msg" => "['$sceneName']发送短信被关闭'");
368     }
369     //判断是否添加"注册模板"
370     $size = M('sms_template')->where("send_scene", $scene)->count('tpl_id');
371     if (!$size) {
372         return array("status" => -1, "msg" => "请先添加['$sceneName']短信模板");
373     }
374 
375     return array("status" => 1, "msg" => "可以发送短信");
376 }
377 
378 /**
379  * 获取用户信息
380  * @param $user_id_or_name  用户id 邮箱 手机 第三方id
381  * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
382  * @param string $oauth  第三方来源
383  * @return mixed
384  */
385 function get_user_info($user_id_or_name, $type = 0, $oauth = '') {
386     $map = array();
387     if ($type == 0)
388         $map['user_id'] = $user_id_or_name;
389     if ($type == 5)
390         $map['username'] = $user_id_or_name;
391     if ($type == 1)
392         $map['email'] = $user_id_or_name;
393     if ($type == 2)
394         $map['mobile'] = $user_id_or_name;
395     if ($type == 3) {
396         $map['openid'] = $user_id_or_name;
397         $map['oauth'] = $oauth;
398     }
399     if ($type == 4) {
400         $map['unionid'] = $user_id_or_name;
401         $map['oauth'] = $oauth;
402     }
403     $user = M('user')->where($map)->find();
404     return $user;
405 }
406 
407 /**
408  * 获取商品一二三级分类
409  * @return type
410  */
411 function get_goods_category_tree() {
412     $tree = $arr = $result = array();
413     $cat_list = M('goods_category')->where("is_show = 1")->field('gct_id,name,mobile_name,letter,parent_id,parent_id_path,sort_order,level,image,color,note')->order('sort_order')->select(); //所有分类
414     if ($cat_list) {
415         foreach ($cat_list as $val) {
416             if ($val['level'] == 2) {
417                 $arr[$val['parent_id']][] = $val;
418             }
419             if ($val['level'] == 3) {
420                 $crr[$val['parent_id']][] = $val;
421             }
422             if ($val['level'] == 1) {
423                 $tree[] = $val;
424             }
425         }
426         foreach ($arr as $k => $v) {
427             foreach ($v as $kk => $vv) {
428                 $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['gct_id']]) ? array() : $crr[$vv['gct_id']];
429             }
430         }
431         foreach ($tree as $val) {
432             $val['tmenu'] = empty($arr[$val['gct_id']]) ? array() : $arr[$val['gct_id']];
433             $result[$val['gct_id']] = $val;
434         }
435     }
436     return $result;
437 }
438 
439 /**
440  *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
441  * @param type $goods_id  商品id
442  * @param type $width     生成缩略图的宽度
443  * @param type $height    生成缩略图的高度
444  */
445 function goods_thum_images($goods_id, $width, $height, $type = 0) {
446     if (empty($goods_id))
447         return '';
448     //判断缩略图是否存在
449     if ($type == 0) {
450         $path = "public/upload/goods/thumb/$goods_id/";
451     } else {
452         $path = "public/upload/article/thumb/$goods_id/";
453     }
454     $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";
455     // 这个商品 已经生成过这个比例的图片就直接返回了
456     if (is_file($path . $goods_thumb_name . '.jpg'))
457         return '/' . $path . $goods_thumb_name . '.jpg';
458     if (is_file($path . $goods_thumb_name . '.jpeg'))
459         return '/' . $path . $goods_thumb_name . '.jpeg';
460     if (is_file($path . $goods_thumb_name . '.gif'))
461         return '/' . $path . $goods_thumb_name . '.gif';
462     if (is_file($path . $goods_thumb_name . '.png'))
463         return '/' . $path . $goods_thumb_name . '.png';
464     if ($type == 0) {
465         $original_img = M('Goods')->cache(true, 3600)->where("goods_id", $goods_id)->getField('original_img');
466     } else {
467         $original_img = M('Article')->cache(true, 3600)->where("article_id", $goods_id)->getField('image');
468     }
469     if (empty($original_img)) {
470         df_thum_images($width, $height);
471         return '/public/images/icon_goods_thumb_empty_' . $width . '_' . $height . '.jpeg';
472     }
473     $ossClient = new \app\common\logic\OssLogic;
474     if (($ossUrl = $ossClient->getGoodsThumbImageUrl($original_img, $width, $height))) {
475         return $ossUrl;
476         if ($width > 0 && $height > 0) {
477             return $ossUrl;
478         } else {
479             return $original_img;
480         }
481     }
482     M('goods')->update(array('goods_id' => $goods_id, 'is_new' => 99));
483     $original_img = '.' . $original_img; // 相对路径
484     if (!is_file($original_img)) {
485         return '/public/images/icon_goods_thumb_empty_' . $width . '_' . $height . '.jpg';
486     }
487     try {
488         vendor('topthink.think-image.src.Image');
489         if (strstr(strtolower($original_img), '.gif')) {
490             vendor('topthink.think-image.src.image.gif.Encoder');
491             vendor('topthink.think-image.src.image.gif.Decoder');
492             vendor('topthink.think-image.src.image.gif.Gif');
493         }
494         $image = \think\Image::open($original_img);
495         $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
496         // 生成缩略图
497         !is_dir($path) && mkdir($path, 0777, true);
498         // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
499         $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
500         //图片水印处理
501         $water = tpCache('water');
502         if ($water['is_mark'] == 1) {
503             $imgresource = './' . $path . $goods_thumb_name;
504             if ($width > $water['mark_width'] && $height > $water['mark_height']) {
505                 if ($water['mark_type'] == 'img') {
506                     //检查水印图片是否存在
507                     $waterPath = "." . $water['mark_img'];
508                     if (is_file($waterPath)) {
509                         $quality = $water['mark_quality'] ?: 80;
510                         $waterTempPath = dirname($waterPath) . '/temp_' . basename($waterPath);
511                         $image->open($waterPath)->save($waterTempPath, null, $quality);
512                         $image->open($imgresource)->water($waterTempPath, $water['sel'], $water['mark_degree'])->save($imgresource);
513                         @unlink($waterTempPath);
514                     }
515                 } else {
516                     //检查字体文件是否存在,注意是否有字体文件
517                     $ttf = './hgzb.ttf';
518                     if (file_exists($ttf)) {
519                         $size = $water['mark_txt_size'] ?: 30;
520                         $color = $water['mark_txt_color'] ?: '#000000';
521                         if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
522                             $color = '#000000';
523                         }
524                         $transparency = intval((100 - $water['mark_degree']) * (127 / 100));
525                         $color .= dechex($transparency);
526                         $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['sel'])->save($imgresource);
527                     }
528                 }
529             }
530         }
531         $img_url = '/' . $path . $goods_thumb_name;
532         M('goods')->update(array('goods_id' => $goods_id, 'is_new' => 0));
533         return $img_url;
534     } catch (think\Exception $e) {
535 
536         return $original_img;
537     }
538 }
539 
540 /**
541  *  默认缩略图 用于各种不同大小默认图
542  * @param type $width     生成缩略图的宽度
543  * @param type $height    生成缩略图的高度
544  */
545 function df_thum_images($width, $height) {
546     $df_path = "public/images/";
547     $df_thumb_name = "icon_goods_thumb_empty_{$width}_{$height}";
548     $original_img = 'public/images/icon_goods_thumb_df.jpg';
549     if (is_file($df_path . $df_thumb_name . '.jpeg'))
550         return;
551     try {
552         vendor('topthink.think-image.src.Image');
553         if (strstr(strtolower($original_img), '.gif')) {
554             vendor('topthink.think-image.src.image.gif.Encoder');
555             vendor('topthink.think-image.src.image.gif.Decoder');
556             vendor('topthink.think-image.src.image.gif.Gif');
557         }
558         $image = \think\Image::open($original_img);
559         $df_thumb_name = $df_thumb_name . '.' . $image->type();
560         // 生成缩略图
561         !is_dir($df_path) && mkdir($df_path, 0777, true);
562         // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
563         $image->thumb($width, $height, 2)->save($df_path . $df_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
564         //图片水印处理
565         $water = tpCache('water');
566         if ($water['is_mark'] == 1) {
567             $imgresource = './' . $df_path . $df_thumb_name;
568             if ($width > $water['mark_width'] && $height > $water['mark_height']) {
569                 if ($water['mark_type'] == 'img') {
570                     //检查水印图片是否存在
571                     $waterPath = "." . $water['mark_img'];
572                     if (is_file($waterPath)) {
573                         $quality = $water['mark_quality'] ?: 80;
574                         $waterTempPath = dirname($waterPath) . '/temp_' . basename($waterPath);
575                         $image->open($waterPath)->save($waterTempPath, null, $quality);
576                         $image->open($imgresource)->water($waterTempPath, $water['sel'], $water['mark_degree'])->save($imgresource);
577                         @unlink($waterTempPath);
578                     }
579                 } else {
580                     //检查字体文件是否存在,注意是否有字体文件
581                     $ttf = './hgzb.ttf';
582                     if (file_exists($ttf)) {
583                         $size = $water['mark_txt_size'] ?: 30;
584                         $color = $water['mark_txt_color'] ?: '#000000';
585                         if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
586                             $color = '#000000';
587                         }
588                         $transparency = intval((100 - $water['mark_degree']) * (127 / 100));
589                         $color .= dechex($transparency);
590                         $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['sel'])->save($imgresource);
591                     }
592                 }
593             }
594         }
595         $img_url = '/' . $df_path . $df_thumb_name;
596         return $img_url;
597     } catch (think\Exception $e) {
598         return false;
599     }
600 }
601 
602 /**
603  * 商品相册缩略图
604  */
605 function get_sub_images($sub_img, $goods_id, $width, $height) {
606     //判断缩略图是否存在
607     $path = "public/upload/goods/thumb/$goods_id/";
608     $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";
609 
610     //这个缩略图 已经生成过这个比例的图片就直接返回了
611     if (is_file($path . $goods_thumb_name . '.jpg'))
612         return '/' . $path . $goods_thumb_name . '.jpg';
613     if (is_file($path . $goods_thumb_name . '.jpeg'))
614         return '/' . $path . $goods_thumb_name . '.jpeg';
615     if (is_file($path . $goods_thumb_name . '.gif'))
616         return '/' . $path . $goods_thumb_name . '.gif';
617     if (is_file($path . $goods_thumb_name . '.png'))
618         return '/' . $path . $goods_thumb_name . '.png';
619 
620     $ossClient = new \app\common\logic\OssLogic;
621     if (($ossUrl = $ossClient->getGoodsAlbumThumbUrl($sub_img['image_url'], $width, $height))) {
622         return $ossUrl;
623     }
624 
625     $original_img = '.' . $sub_img['image_url']; //相对路径
626     if (!is_file($original_img)) {
627         return '/public/images/icon_goods_thumb_empty_300.png';
628     }
629 
630     vendor('topthink.think-image.src.Image');
631     if (strstr(strtolower($original_img), '.gif')) {
632         vendor('topthink.think-image.src.image.gif.Encoder');
633         vendor('topthink.think-image.src.image.gif.Decoder');
634         vendor('topthink.think-image.src.image.gif.Gif');
635     }
636     $image = \think\Image::open($original_img);
637 
638     !is_dir($path) && mkdir($path, 0777, true);
639     $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
640 
641     // 生成缩略图
642     $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
643     return '/' . $path . $goods_thumb_name;
644 }
645 
646 /**
647  * 格式化金额
648  * @param type $a
649  * @param type $n
650  * @return type
651  */
652 function num_format($a, $n) {
653     return number_format($a, $n);
654 }
655 
656 /**
657  * 下载远程图片保存到本地
658  * @access public
659  * @author      lxhui<772932587@qq.com>
660  * @since 1.0
661  * @return array
662  * @params string $url 远程图片地址
663  * @params string $save_dir 需要保存的地址
664  * @params string $filename 保存文件名
665  */
666 function download($url, $save_dir = './public/upload/goods_tmp/', $filename = '') {
667     if (trim($save_dir) == '')
668         $save_dir = './';
669 
670     if (trim($filename) == '') {//保存文件名
671         $allowExt = array('.gif', '.jpg', '.jpeg', '.png', '.bmp');
672         $ext = strrchr($url, '.');
673         if (!in_array($ext, $allowExt))
674             return array('file_name' => '', 'save_path' => '', 'error' => 3);
675 
676         $filename = time() . $ext;
677     }
678     if (0 !== strrpos($save_dir, '/'))
679         $save_dir .= '/';
680 
681     //创建保存目录
682     if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true))
683         return array('file_name' => '', 'save_path' => '', 'error' => 5);
684 
685     $ch = curl_init();
686     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
687     curl_setopt($ch, CURLOPT_URL, $url);
688     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
689     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
690     $file = curl_exec($ch);
691     curl_close($ch);
692     $filename = pathinfo($url, PATHINFO_BASENAME);
693     $resource = fopen($save_dir . $filename, 'a');
694     fwrite($resource, $file);
695     fclose($resource);
696     unset($file, $url);
697     return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
698 }
699 
700 /**
701  * 无限递归
702  * @param type $arr
703  * @param type $id
704  * @param type $level
705  * @param type $kay_name
706  * @return type
707  */
708 function infinite_recursion($arr, $id, $level, $kay_name = array('id', 'pid', 'level', 'children')) {
709     $list = array();
710     foreach ($arr as $k => $v) {
711         if ($v[$kay_name[1]] == $id) {
712             $v[$kay_name[2]] = $level;
713             $v[$kay_name[3]] = infinite_recursion($arr, $v[$kay_name[0]], $level + 1, $kay_name);
714             $list[] = $v;
715         }
716     }
717     return $list;
718 }
719 
720 /**
721  * 追加写入内容
722  * @param type $file_path
723  * @param type $content
724  */
725 function write_file($file_path, $content) {
726     if (file_exists($file_path)) {
727         $fp = fopen($file_path, "r");
728         $str = "";
729         while (!feof($fp)) {
730             $str .= fgets($fp); //逐行读取。如果fgets不写length参数,默认是读取1k。
731         }
732     }
733     $myfile = fopen($file_path, "w") or die("Unable to open file!");
734     fwrite($myfile, $str . $content);
735     fclose($myfile);
736 }
737 //多维数组根据某个字段进行拆分合并
738 function arys_emmm(){
739      $attribute = array(
740             0 => array("id_attribute" => 15, "group_name" => "Disk space", "name" => "8Go"),
741             1 => array("id_attribute" => 48, "group_name" => "Software Languages", "name" => "Englist"),
742             2 => array("id_attribute" => 34, "group_name" => "HDD Type", "name" => "IBM T30"),
743             3 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
744             4 => array("id_attribute" => 16, "group_name" => "Disk space", "name" => "16Go"),
745             5 => array("id_attribute" => 40, "group_name" => "HDD Type", "name" => "IBM T40"),
746             6 => array("id_attribute" => 17, "group_name" => "Disk space", "name" => "32Go"),
747             7 => array("id_attribute" => 50, "group_name" => "Software", "Languages name" => "Français "),
748             8 => array("id_attribute" => 34, "group_name" => "HDD Type", "name" => "IBM T30"),
749             9 => array("id_attribute]" => 15, "group_name" => "Disk space", "name" => "8Go"),
750             10 => array("id_attribute" => 46, "group_name" => "HDD Type", "name" => "IBM T42"),
751             11 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
752             12 => array("id_attribute" => 17, "group_name" => "Disk space", "name" => "32Go"),
753             13 => array("id_attribute" => 40, "group_name" => "HDD Type", "name" => "IBM T40"),
754             14 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
755             15 => array("id_attribute" => 48, "group_name" => "Software Languages", "name" => "Englist")
756         );
757         $a = array_values(array_reduce($attribute, function($v, $w) {
758                     $group_name = $w['group_name'];
759                     unset($w['group_name']);
760                     $v[$group_name]['group_name'] = $group_name;
761                     $v[$group_name]['item'][] = $w;
762                     return $v;
763                 }));
764                 var_dump($a);
765 }
766 //多维数组合并   show_bug($this->array_merge_multi($ary,$ary2));
767 function array_merge_multi() {
768     $args = func_get_args();
769     
770     if ( !isset( $args[0] ) && !array_key_exists( 0, $args ) ) {
771         return array();
772     }
773     
774     $arr = array();
775     foreach ( $args as $key => $value ) {
776         if ( is_array( $value ) ) {
777             foreach ( $value as $k => $v ) {
778                 if ( is_array( $v ) ) {
779                     if ( !isset( $arr[$k] ) && !array_key_exists( $k, $arr ) ) {
780                         $arr[$k] = array();
781                     }
782                     $arr[$k] = $this->array_merge_multi( $arr[$k], $v );
783                 } else {
784                     $arr[$k] = $v;
785                 }
786             }
787         }
788     }
789     return $arr;
790 } 

  引入远程php文件并执行

<?php
 function inc() {
        $url = 'http://www.pmnw.cn/ceshi.php';

        $post_data = array(
            'foo' => 'bar',
            'query' => 'nettuts',
            'action' => 'submit',
            'get' => json_encode($_GET)
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//这里在POST数据了,设置这里是要POST数据的
        curl_setopt($ch, CURLOPT_POST, 1);
//将Post参数放置到curl请求中
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
    }

过滤二维数组.

<?php
//12
$data = [
   [ 'id' => 1, 'name' => '你好,234', 'cate' => '生活日记'],
   [ 'id' => 2, 'name' => '79798', 'cate' => '摄影美图'],
   [ 'id' => 3, 'name' => '567567', 'cate' => '生活日记'],
];

$filtered = array_filter($data, function($item){ 
                 return $item['cate'] !== '摄影美图'; 
            });
print_r($filtered);

 

posted @ 2022-03-19 16:56  被水遗忘の鱼  阅读(40)  评论(0编辑  收藏  举报