PHP常用的一些屌炸天的技巧(一)

大部分有两三年工作经验的PHPer,都必定积累了不少在日常开发中使用的小技巧。从前端,接口开发,团队编程规范,模块化和前辈们分享的个人经验中总结出一些小技巧。这些技能都能大大地提高我们日常开发的效率,提升我们的代码质量,更能让你省下了很多看看书,看看博客,找妹子聊聊天的时间。以下是我个人从工作经验中总结的一些编程小技巧,其中可能也会包括一些前辈们分享的经验,如有更好的实现方法,可以留言分享一下您的宝贵经验,在下一次分享或者后续遍中进而补充。

一.常用函数/方法:

谈到函数,我的话就多了,在分享PHP小技巧中,莫过于大家都熟知的PHP函数有很多很多,那么日常工作中常用的大家也有很多离不开你的项目代码,离不开你的function.php或者commont.php函数库啦。以下是我的一些常用的函数,分享给大家。

1.高亮显示的断点调试工具(灵活实用它可以不局限于断点和backgroup):

   
   
  1. function debug($data){
  2. if( empty($data)){
  3. var_dump($data);
  4. die;
  5. }
  6. if(!is_array($data)){
  7. echo "<pre style='background-color: #000;color: #fff;font-size: 14px;min-height: 100px;line-height: 50px;'>";
  8. echo "<span style='margin-left: 20px;font-size: 18px;'>";
  9. print_r($data);
  10. echo "</span>";
  11. echo "</pre>";
  12. die;
  13. }
  14. echo "<pre style='background-color: #000;color: #fff;font-size: 14px;min-height: 100px;'>";
  15. echo "<br /><br /><br /><span style='margin-left: 20px;font-size: 13px;'>";
  16. print_r($data);
  17. echo "</span><br /><br /><br />";
  18. echo "</pre>";
  19. die;
  20. }
2.递归无限极分类(要坚决鄙视写数据库操作在循环里或者写在递归里的垃圾代码):

   
   
  1. /* @param $data array 数据
  2. * @param $pid int 父类关系值
  3. * @param $parentFieldstring 父类字段
  4. * @param $pkField string 主键字段
  5. * return array
  6. */
  7. function getTreesPro($data,$pid='0',$parentField='pid',$pkField='id'){
  8. $tree = array();
  9. foreach($data as $k=>$v){
  10. if($v[$parentField] == $pid){
  11. $temp = getTreesPro($data,$v[$pkField]); //$data是对象则改为$v->$pkField
  12. if(! empty($temp)){
  13. //分层
  14. $v[ 'son']= getTreesPro($data,$v[$pkField]);
  15. }
  16. $tree[] = $v;
  17. }
  18. }
  19. return $tree;
  20. }
3.数组转对象

   
   
  1. function arrayToObject($arr){
  2. if(is_array($arr)){
  3. return (object) array_map( __FUNCTION__, $arr);
  4. } else{
  5. return $arr;
  6. }
  7. }
4.对象转数组

   
   
  1. function object2array(&$object) {
  2. $object = json_decode( json_encode( $object), true);
  3. return $object;
  4. }
5.生成唯一订单号

   
   
  1. function generateJnlNo() {
  2. date_default_timezone_set( 'PRC');
  3. $yCode = array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
  4. $orderSn = '';
  5. $orderSn .= $yCode[(intval(date( 'Y')) - 1970) % 10];
  6. $orderSn .= strtoupper(dechex(date( 'm')));
  7. $orderSn .= date( 'd').substr(time(), -5);
  8. $orderSn .= substr(microtime(), 2, 5);
  9. $orderSn .= sprintf( '%02d', mt_rand( 0, 99));
  10. //echo $orderSn,PHP_EOL; //得到唯一订单号:G107347128750079
  11. return $orderSn;
  12. }
6.将一个二维数组转换为 HashMap,并返回结果

   
   
  1. /**
  2. * 用法1:
  3. * @code php
  4. * $rows = array(
  5. * array( 'id' => 1, 'value' => '1-1'),
  6. * array( 'id' => 2, 'value' => '2-1'),
  7. *);
  8. * $hashmap = Helper_Array::hashMap( $rows, 'id', 'value');
  9. *
  10. * dump( $hashmap);
  11. * // 输出结果为
  12. * // array(
  13. * // 1 => '1-1',
  14. * // 2 => '2-1',
  15. * //)
  16. * @endcode
  17. *
  18. * 如果省略 $value_field 参数,则转换结果每一项为包含该项所有数据的数组。
  19. *
  20. * 用法2:
  21. * @code php
  22. * $rows = array(
  23. * array( 'id' => 1, 'value' => '1-1'),
  24. * array( 'id' => 2, 'value' => '2-1'),
  25. *);
  26. * $hashmap = Helper_Array::hashMap( $rows, 'id');
  27. *
  28. * dump( $hashmap);
  29. * // 输出结果为
  30. * // array(
  31. * // 1 => array( 'id' => 1, 'value' => '1-1'),
  32. * // 2 => array( 'id' => 2, 'value' => '2-1'),
  33. * //)
  34. * @endcode
  35. *
  36. * @param array $arr 数据源
  37. * @param string $key_field 按照什么键的值进行转换
  38. * @param string $value_field 对应的键值
  39. *
  40. * @ return array 转换后的 HashMap 样式数组
  41. */
  42. function to_hashmap( $arr, $key_field, $value_field = null){
  43. $ret = array();
  44. if ( $value_field){
  45. foreach ( $arr as $row){
  46. $ret[ $row[ $key_field]] = $row[ $value_field];
  47. }
  48. }
  49. else{
  50. foreach ( $arr as $row){
  51. $ret[ $row[ $key_field]] = $row;
  52. }
  53. }
  54. return $ret;
  55. }
7.从二位数组中,取出某字段的所有结果(包含重复结果)

如从$brandList数据中取出所有id的值:$ids = array_column($brandList,'id'); 去重结果 $ids= array_unique(array_column($brandList,'id'));


   
   
  1. if (!function_exists( 'array_column')) {
  2. /**
  3. * Returns the values from a single column of the input array, identified by
  4. * the $columnKey.
  5. *
  6. * Optionally, you may provide an $indexKey to index the values in the returned
  7. * array by the values from the $indexKey column in the input array.
  8. *
  9. * @param array $input A multi-dimensional array (record set) from which to pull
  10. * a column of values.
  11. * @param mixed $columnKey The column of values to return. This value may be the
  12. * integer key of the column you wish to retrieve, or it
  13. * may be the string key name for an associative array.
  14. * @param mixed $indexKey (Optional.) The column to use as the index/keys for
  15. * the returned array. This value may be the integer key
  16. * of the column, or it may be the string key name.
  17. * @return array
  18. */
  19. function array_column($input = null, $columnKey = null, $indexKey = null){
  20. // Using func_get_args() in order to check for proper number of
  21. // parameters and trigger errors exactly as the built-in array_column()
  22. // does in PHP 5.5.
  23. $argc = func_num_args();
  24. $params = func_get_args();
  25. if ($argc < 2) {
  26. trigger_error( "array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
  27. return array();
  28. }
  29. if (!is_array($params[ 0])) {
  30. trigger_error( 'array_column() expects parameter 1 to be array, ' . gettype($params[ 0]) . ' given', E_USER_WARNING);
  31. return array();
  32. }
  33. if (!is_int($params[ 1])
  34. && !is_float($params[ 1])
  35. && !is_string($params[ 1])
  36. && $params[ 1] !== null
  37. && !(is_object($params[ 1]) && method_exists($params[ 1], '__toString'))
  38. ) {
  39. trigger_error( 'array_column(): The column key should be either a string or an integer', E_USER_WARNING);
  40. return array();
  41. }
  42. if ( isset($params[ 2])
  43. && !is_int($params[ 2])
  44. && !is_float($params[ 2])
  45. && !is_string($params[ 2])
  46. && !(is_object($params[ 2]) && method_exists($params[ 2], '__toString'))
  47. ) {
  48. trigger_error( 'array_column(): The index key should be either a string or an integer', E_USER_WARNING);
  49. return array();
  50. }
  51. $paramsInput = $params[ 0];
  52. $paramsColumnKey = ($params[ 1] !== null) ? (string) $params[ 1] : null;
  53. $paramsIndexKey = null;
  54. if ( isset($params[ 2])) {
  55. if (is_float($params[ 2]) || is_int($params[ 2])) {
  56. $paramsIndexKey = (int) $params[ 2];
  57. } else {
  58. $paramsIndexKey = (string) $params[ 2];
  59. }
  60. }
  61. $resultArray = array();
  62. foreach ($paramsInput as $row) {
  63. $key = $value = null;
  64. $keySet = $valueSet = false;
  65. if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
  66. $keySet = true;
  67. $key = (string) $row[$paramsIndexKey];
  68. }
  69. if ($paramsColumnKey === null) {
  70. $valueSet = true;
  71. $value = $row;
  72. } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
  73. $valueSet = true;
  74. $value = $row[$paramsColumnKey];
  75. }
  76. if ($valueSet) {
  77. if ($keySet) {
  78. $resultArray[$key] = $value;
  79. } else {
  80. $resultArray[] = $value;
  81. }
  82. }
  83. }
  84. return array_unique($resultArray);
  85. }
  86. }
8.客户端缓存方法

   
   
  1. public function cache($seconds_to_cache = 3600){
  2. $ts = gmdate( "D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  3. header( "Expires: $ts");
  4. header( "Pragma: cache");
  5. header( "Cache-Control: max-age=$seconds_to_cache");
  6. }
9.客户端不缓存方法

   
   
  1. public function disCache(){
  2. $ts = gmdate( "D, d M Y H:i:s",strtotime( '-1 year')) . " GMT";
  3. header( "Expires: $ts");
  4. header( "Last-Modified: $ts");
  5. header( "Pragma: no-cache");
  6. header( "Cache-Control: no-cache, must-revalidate");
  7. }
10.返回上一个页面来源

   
   
  1. public function referer(){
  2. return $_SERVER[ 'HTTP_REFERER'];
  3. }
11.分页方法(在api方面用得比较多)

   
   
  1. public function pageinfo(){
  2. $pageinfo = new \stdClass;
  3. $pageinfo->length = isset($_GET[ 'length']) ? $_GET[ 'length'] : $this->length;
  4. $pageinfo->page = isset($_GET[ 'page']) ? $_GET[ 'page'] : 1;
  5. $pageinfo->end_id = isset($_GET[ 'end_id']) ? $_GET[ 'end_id'] : 1;
  6. $pageinfo->offset= $pageinfo->page<= 1 ? 0 : ($pageinfo->page -1) * $pageinfo->length;
  7. $pageinfo->totalNum = $pageinfo->totalNum? $pageinfo->totalNum : 0;
  8. $pageinfo->totalPage = $pageinfo->totalNum / $pageinfo->length;
  9. return $pageinfo;
  10. }


猜你喜欢

转载自blog.csdn.net/qq_16059847/article/details/88355017
今日推荐