欢迎光临
我们一直在努力

thinkPHP框架开发laobingcms公共方法的代码汇总

<?
use think\Env;
use think\Cookie;
use think\Db;
// 应用公共文件
//获取目录
function getRoot($file){
    $fileUrl=str_replace('\\','/',realpath(dirname($file).'/'))."/";
    $genIndex=strpos($fileUrl,'/Application/');
    if($genIndex>0){
    $rootPath=substr($fileUrl,0,$genIndex).'/';//~/home/web/zdm_jsens_com/public_html
    return $rootPath;
    }
}
//获取路径
function getRootDirName(){
    if(PHP_OS === 'WINNT'){//liunx
        $env=new Env();
        $root=$env->get('ROOT_PATH');
        $arr = explode('/',rtrim($root,'/'));
    }else{
        $arr = explode('\\',rtrim($root,'\\'));
    }
    return $arr[count($arr)-1];
}
//获取目录列表
function getDir($dir) {
    $dirArray[]=NULL;
    if (false != ($handle = opendir ( $dir ))) {
        $i=0;
        while ( false !== ($file = readdir ( $handle )) ) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".."&&!strpos($file,".")) {
                $dirArray[$i]=$file;
                $i++;
            }
        }
        //关闭句柄
        closedir ( $handle );
    }
    return $dirArray;
}
//获取文件列表
function getFile($dir) {
    $fileArray[]=NULL;
    if (false != ($handle = opendir ( $dir ))) {
        $i=0;
        while ( false !== ($file = readdir ( $handle )) ) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".."&&strpos($file,".")) {
                $fileArray[$i]=$file;
                if($i==100){
                    break;
                }
                $i++;
            }
        }
        //关闭句柄
        closedir ( $handle );
    }
    return $fileArray;
}
//获取域名目录
function dirna($wz){
        $last=$_SERVER['DOCUMENT_ROOT'];
        $last=dirname(dirname($last)).'\\';//根目录同级
        if(strpos($wz,'www') !==false){//检测是否包含www
         $mulu=$wz;
        }else{
         $mulu='www.'. $wz; 
        }
        $str=str_replace('www.','',$mulu);//去掉www.
        $dir = $last.$str; //F:\php\phpstudy_pro\WWW\demo1.com文件夹路径
        if(is_dir($dir))
        {
           $floder= getDir($dir);
           $data=$dir.'\\'.$floder[2].'\\';
           if(is_dir($data)){
            $dir=opendir($data);
            $a=getFile($data);
            $file=$a[2];
           //  $config=$data.$a[0];
           // echo $config;exit;
            $way=$data.$file;
            require($way);//引入数据库配置
            $shuju=Db::connect('mysql://'.$mydbuser.':'.$mydbpwd.'@'.$mydbhost.':3306/'.$mydbname.'#utf8');
            $con='mysql://'.$mydbuser.':'.$mydbpwd.'@'.$mydbhost.':3306/'.$mydbname.'#utf8';
            // Cache::set('dbcon',$con,0);
            cookie('con', $con);
            $shuju=$shuju->name('80cms_config')->select();
             // dump($shuju);
            $pchtml= $last.$wz.'/'.$shuju[0]["c_temppath"].'/default/index.htm';       
            return $pchtml;

           }
        }
        else
        {
            echo $dir."此目录不存在,请重新输入!";
        }  
}

//更新栏目的文章数量
function TagLib_list($content,$list){

    preg_match_all('/\[tag:(.*?)\]/',$content,$arry); //读取标签
    $tag = $arry[0]; //匹配标签
    $key = $arry[1]; //标签字段
    $str='';
    for($i=0;$i<count($list);$i++)
    {
        $c = $content; //读取模板内容
        //替换标签
        foreach($tag as $k=>$v){
            //分割字符串,如果有函数那么执行函数后在输出
            $arr = explode('|',$key[$k]);
            $th = $list[$i][$arr[0]];
            if($arr[1]){
                $arr[1] = str_replace('###',$list[$i][$arr[0]],$arr[1]);
                $a = '$th'." =$arr[1]";
                eval($a.';');
            }
            $c = str_replace($v,$th,$c);
        }
        $str.=$c;
    }
    return $str;
}
/*
 *    info标签格式化
 *    参数:$key 要处理的值  $fun 从模板中传入的要执行的函数
 *    返回值:字符串
 */
function TagLib_info($key,$fun){
    //有输出值则输出
    if($key){
        //如果使用函数
        if($fun){$return  = str_replace('###',$key,$fun);}else{$return =$key;}
        //如果值不为空
        if($return){
            $str  = '<?php ';
            $str .= 'echo '.$return .';';
            $str .= ' ?>';
        }
    }
    return $str;
}
// * 获取分类所有子分类
function get_category_children($cid)
{
    if (empty($cid)) {
        return false;
    }
    $children = Db::name('80cms_column')->where(['c_parentid' => $cid])->select();
 // dump($children);exit;
    return array2tree($children);
}
function findChild(&$arr,$id){
        $childs=array();
        // dump($arr);exit;

        foreach ($arr as $k => $v){
            if($v['c_parentid']== $id){
                $childs[]=$v;
            }
        }
        return $childs;
    }

//递归获取子栏目id
function Fun_column_allid ($parent_id = 0, $level = 0, $arrtext="", $maxlevel = 0)
{
    if($parent_id<>"" and preg_match("/^\d*$/",$parent_id) and $parent_id>0)
    {
        if($level==0){$arrtext=$parent_id;}
        $maxleveltj="";if($maxlevel<>"" and preg_match("/^\d*$/",$maxlevel) and $maxlevel>0){$maxleveltj=" and c_level<".$maxlevel."";}
        // $result_zi = "SELECT c_id, c_name from 80cms_column where c_key=1 and c_parentid='".intval($parent_id)."'".$maxleveltj."";
        $row_zi=Db::name('80cms_column')->where(['c_key'=>1,'c_parentid'=>$parent_id])->find();
        dump($row_zi);exit;
        while ($row_zi) 
        {
            $arrtext=Fun_column_allid($row_zi['c_id'],$level + 1,$arrtext.",".$row_zi ['c_id']."",$maxlevel);
        }
    }
    // dump($arrtext);exit;
    return $arrtext;
}

/**
 * 根据分类ID获取文章列表(不包括子分类)
 * @param int $cid 分类ID
 * @return array|bool|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_articles_by_category_id($cid,$n=10)
{
    if (empty($cid)) {
        return false;
    }
    $data_list = Db::name('archives')->where(['typeid'=>$cid])->limit($n)->select();
    return $data_list;
}

/**
 *  * 根据分类ID获取文章列表(包括子分类)
 * @param int $cid 分类ID
 * @param int $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return array|bool|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}

/**
 * 根据分类ID获取文章列表,带分页(包括子分类)
 * @param int   $cid   分类ID
 * @param int $page_size 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|\think\Paginator
 * @throws \think\exception\DbException
 */
function get_articles_by_cid_paged($cid, $page_size = 15, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->paginate($page_size);

    return $article_list;
}

/**
 * 数组层级缩进转换
 * @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;
}

/**
 * 构建层级(树状)数组
 * @param array  $array          要进行处理的一维数组,经过该函数处理后,该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = "c_id", $child_key_name = "c_parentid")
{

    $counter = array_children_count($array, $child_key_name);
   // print_r($counter);exit;
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];

    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
         // dump($temp);exit;
        if (isset($counter[$temp['c_id']]) && $counter[$temp['c_id']] > 0) {
            array_push($array, $temp);
               dump($array);exit;
        } else {
            if ($temp[$child_key_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$child_key_name], $temp, $pid_name);
            }
            dump($array);
            exit;
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}
/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[0] = $count;
    }
   // dump($counter);exit;
    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        // dump($item);exit;
        if ($item['c_id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

//创建文件
function MakeHtmlFile($file_name, $content)
{
  if (!file_exists (dirname($file_name)))
  {
    echo "目录不存在!";
    mysql_close();
    exit;
  }  
  if(!$fp = fopen($file_name, "w"))
  { 
    return false;
  } 
  if(!fwrite($fp, $content))
  { 
    echo "";
    //exit;
    fclose($fp);
    return false;
  }
  fclose($fp);
  @chmod($file_name,0666);
  return true;
}
//创建文件结束
/**
 * 判断是否为手机访问
 * @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 $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}
赞(0) 打赏
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 ivillcn@qq.com 举报,一经查实,本站将立刻删除。
文章名称:《thinkPHP框架开发laobingcms公共方法的代码汇总》
文章链接:https://www.bilibiji.com/article/212.html

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

微信扫一扫

登录

找回密码

注册