11種PHP常用函數分享

來源:互聯網
上載者:User
這次給大家帶來11種PHP常用函數的知識分享,這些技能都能大大地提高我們日常開發的效率,提升我們的代碼品質,下一起跟隨小編來看一下。

1.高亮顯示的斷點調試工具(靈活實用它可以不局限於斷點和backgroup):

function debug($data){    if(empty($data)){        var_dump($data);        die;    }    if(!is_array($data)){        echo "<pre style='background-color: #000;color: #fff;font-size: 14px;min-height: 100px;line-height: 50px;'>";        echo "<span style='margin-left: 20px;font-size: 18px;'>";        print_r($data);        echo "</span>";        echo "</pre>";        die;    }    echo "<pre style='background-color: #000;color: #fff;font-size: 14px;min-height: 100px;'>";    echo "<br /><br /><br /><span style='margin-left: 20px;font-size: 13px;'>";    print_r($data);    echo "</span><br /><br /><br />";    echo "</pre>";    die;}
2.遞迴無限極分類(要堅決鄙視寫資料庫操作在迴圈裡或者寫在遞迴裡的垃圾代碼):
/* @param   $data  array   資料* @param   $pid   int     父類別關係值* @param   $parentFieldstring  父類欄位* @param $pkField string  主鍵欄位* return array*/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.將一個二維數群組轉換為 HashMap,並返回結果
/*** 用法1:* @code php* $rows = array(*     array('id' => 1, 'value' => '1-1'),*     array('id' => 2, 'value' => '2-1'),*);* $hashmap = Helper_Array::hashMap($rows, 'id', 'value');** dump($hashmap);*   // 輸出結果為*   // array(*   //   1 => '1-1',*   //   2 => '2-1',*   //)* @endcode** 如果省略 $value_field 參數,則轉換結果每一項為包含該項所有資料的數組。** 用法2:* @code php* $rows = array(*     array('id' => 1, 'value' => '1-1'),*     array('id' => 2, 'value' => '2-1'),*);* $hashmap = Helper_Array::hashMap($rows, 'id');** dump($hashmap);*   // 輸出結果為*   // array(*   //   1 => array('id' => 1, 'value' => '1-1'),*   //   2 => array('id' => 2, 'value' => '2-1'),*   //)* @endcode** @param array $arr 資料來源* @param string $key_field 按照什麼鍵的值進行轉換* @param string $value_field 對應的索引值** @return array 轉換後的 HashMap 樣式數組*/function to_hashmap($arr, $key_field, $value_field = null){     $ret = array();     if ($value_field){         foreach ($arr as $row){             $ret[$row[$key_field]] = $row[$value_field];         }     }      else{         foreach ($arr as $row){             $ret[$row[$key_field]] = $row;         }     }     return $ret;}
7.從二位元組中,取出某欄位的所有結果(包含重複結果)

如從$brandList資料中取出所有id的值:$ids = array_column($brandList,'id'); 去重結果 $ids= array_unique(array_column($brandList,'id'));

if (!function_exists('array_column')) {   /**    * Returns the values from a single column of the input array, identified by    * the $columnKey.    *    * Optionally, you may provide an $indexKey to index the values in the returned    * array by the values from the $indexKey column in the input array.    *    * @param array $input A multi-dimensional array (record set) from which to pull    *                     a column of values.    * @param mixed $columnKey The column of values to return. This value may be the    *                         integer key of the column you wish to retrieve, or it    *                         may be the string key name for an associative array.    * @param mixed $indexKey (Optional.) The column to use as the index/keys for    *                        the returned array. This value may be the integer key    *                        of the column, or it may be the string key name.    * @return array    */   function array_column($input = null, $columnKey = null, $indexKey = null){       // Using func_get_args() in order to check for proper number of       // parameters and trigger errors exactly as the built-in array_column()       // does in PHP 5.5.       $argc = func_num_args();       $params = func_get_args();       if ($argc < 2) {           trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);           return array();       }       if (!is_array($params[0])) {           trigger_error('array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given', E_USER_WARNING);           return array();       }       if (!is_int($params[1])           && !is_float($params[1])           && !is_string($params[1])           && $params[1] !== null           && !(is_object($params[1]) && method_exists($params[1], '__toString'))       ) {           trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);           return array();       }       if (isset($params[2])           && !is_int($params[2])           && !is_float($params[2])           && !is_string($params[2])           && !(is_object($params[2]) && method_exists($params[2], '__toString'))       ) {           trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);           return array();       }       $paramsInput = $params[0];       $paramsColumnKey = ($params[1] !== null) ? (string) $params[1] : null;        $paramsIndexKey = null;       if (isset($params[2])) {           if (is_float($params[2]) || is_int($params[2])) {               $paramsIndexKey = (int) $params[2];           } else {               $paramsIndexKey = (string) $params[2];           }       }        $resultArray = array();        foreach ($paramsInput as $row) {            $key = $value = null;           $keySet = $valueSet = false;           if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {               $keySet = true;               $key = (string) $row[$paramsIndexKey];           }            if ($paramsColumnKey === null) {               $valueSet = true;               $value = $row;           } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {               $valueSet = true;               $value = $row[$paramsColumnKey];           }            if ($valueSet) {               if ($keySet) {                   $resultArray[$key] = $value;               } else {                   $resultArray[] = $value;               }           }       }        return array_unique($resultArray);   } }
8.用戶端緩衝方法
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");}
9.用戶端不緩衝方法
 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");}
10.返回上一個頁面來源
public function referer(){    return $_SERVER['HTTP_REFERER'];}
11.分頁方法(在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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.