PHP中的一些小技巧

1、高亮显示判断显示

function debug($data){
    if(empty($data)){
        var_dump($data);
        die;
    }

    if(!is_array($data)){
        echo "
";
        echo "";
        print_r($data);
        echo "";
        echo "
"
; die; } echo "
";
    echo "


"; print_r($data); echo "


"
; echo "
"
; die; }

2、递归无限极分类(要坚决鄙视写数据库操作在循环里或者写在递归里的垃圾代码)

function getTreesPro($data,$pid='0',$parentField='pid',$pkField='id'){
        $tree =array();
        foreach($data as $k=>$v){

            if($v[$parentField] == $pid){
                $temp   =   getTreesPro($data,$v[$pkField]);//$data是对象则改为$v->$pkField
                if(!empty($temp)){
                //分层
                    $v['son']= getTreesPro($data,$v[$pkField]);
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }

3、数组转对象

function arrayToObject($arr){
    if(is_array($arr)){
        return (object) array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}

4、对象转数组

function object2array(&$object) {
    $object =  json_decode( json_encode( $object),true);
    return  $object;
}

5、生成唯一订单

function generateJnlNo() {
   date_default_timezone_set('PRC');
   $yCode    = array('A','B','C','D','E','F','G','H','I','J');
   $orderSn  = '';
   $orderSn .= $yCode[(intval(date('Y')) - 1970) % 10];
   $orderSn .= strtoupper(dechex(date('m')));
   $orderSn .= date('d').substr(time(), -5);
   $orderSn .= substr(microtime(), 2, 5);
   $orderSn .= sprintf('%02d', mt_rand(0, 99));
   //echo $orderSn,PHP_EOL;     //得到唯一订单号:G107347128750079
   return $orderSn;
}

6、客户端缓存办法

public function cache($seconds_to_cache = 3600){
    $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
    header("Expires: $ts");
    header("Pragma: cache");
    header("Cache-Control: max-age=$seconds_to_cache");
}

7、客户端不缓存办法

 public function disCache(){
    $ts = gmdate("D, d M Y H:i:s",strtotime('-1 year')) . " GMT";
    header("Expires: $ts");
    header("Last-Modified: $ts");
    header("Pragma: no-cache");
    header("Cache-Control: no-cache, must-revalidate");
}

8、返还上一个页面来源

public function referer(){
    return $_SERVER['HTTP_REFERER'];
}

9、分页方法,在api页面用的比较多

public function pageinfo(){
    $pageinfo               = new \stdClass;
    $pageinfo->length       = isset($_GET['length']) ? $_GET['length'] : $this->length;
    $pageinfo->page         = isset($_GET['page']) ? $_GET['page'] : 1;
    $pageinfo->end_id       = isset($_GET['end_id']) ? $_GET['end_id'] : 1;
    $pageinfo->offset= $pageinfo->page<=1 ? 0 : ($pageinfo->page-1) * $pageinfo->length;
    $pageinfo->totalNum     = $pageinfo->totalNum? $pageinfo->totalNum  : 0;
    $pageinfo->totalPage    = $pageinfo->totalNum / $pageinfo->length;

    return $pageinfo;
}

你可能感兴趣的:(学习)