您好,欢迎访问一九零五行业门户网

11种PHP常用函数分享

这次给大家带来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;
以上就是11种php常用函数分享的详细内容。
其它类似信息

推荐信息