PHP basic Function Summary _php tips

Source: Internet
Author: User
Tags array sort chr closure decrypt explode md5 ord strlen

1. Count the number of elements in an array

$arr = Array (
   ' 1011,1003,1008,1001,1000,1004,1012 ', '
   1009 ', ' 1011,1003,1111 '
  );
$result = Array ();
foreach ($arr as $str) {
 $str _arr = Explode (', ', $str);
 foreach ($str _arr as $v) {
  //$result [$v] = Isset ($result [$v])? $result [$v]: 0;
  $result [$v] = $result [$v] + 1;
  $result [$v] = Isset ($result [$v])? $result [$v]+1:1;
 }
}
Print_r ($result);
Array
(
[1011] => 2
[1003] => 2
[1008] => 1
[1001] => 1
[1000] => 1
[1004] => 1
[1012] => 1
[1009] => 1
[1111] => 1
)

2. Cycle Delete Directory

function Cleanup_directory ($dir) {
 foreach (new Directoryiterator ($dir) as $file) {
  if ($file->isdir ()) { C31/>if (! $file->isdot ()) {
    cleanup_directory ($file->getpathname ());
   }
  } else {
    unlink ($ File->getpathname ());
  }
  RmDir ($dir);

3. Infinite Polar classification Spanning tree

function Generatetree ($items) {$tree = array (); foreach ($items as $item) {if (Isset ($items [$item [' pid ']]) {$items [$item [' pid ']][' son '] [] = & $items [' ID
    ']];
    }else{$tree [] = & $items [$item [' id ']];
} return $tree; The function generateTree2 ($items) {foreach ($items as $item) $items [$item [' pid ']][' son '] [$item [' id ']] = & $items [$i
  tem[' id ']]; return Isset ($items [0][' son '])?
$items [0][' son ']: Array (); $items = Array (1 => array (' ID ' => 1, ' pid ' => 0, ' name ' => ' Anhui Province '), 2 => array (' ID ' => 2, ' pid ' = > 0, ' name ' => ' Zhejiang province ', 3 => array (' ID ' => 3, ' pid ' => 1, ' name ' => ' Hefei '), 4 => array (' ID ' =>
4, ' PID ' => 3, ' name ' => ' Changfeng County '), 5 => array (' ID ' => 5, ' pid ' => 1, ' name ' => ' Anqing '),);
Print_r (Generatetree ($items));
/** * How to take data formatted tree data/$tree = Generatetree ($items); function Gettreedata ($tree) {foreach ($tree as $t) {echo $t [' name ']. '
    <br> '; if (Isset ($t [' SoN ']) {gettreedata ($t [' son ']);

 }
  }
}

4. Array sort A-b is a numeric array. When you encounter a string, you need to

var test = [' ab ', ' AC ', ' BD ', ' BC '];
Test.sort (function (A, b) {
  if (a < b) {
    return-1
  }

  if (a > B) {return
    1;
  }

  return 0;
});

5.array_reduce

$raw = [1,2,3,4,5,];
The third parameter of the array_reduce is the initial value of the $result
array_reduce ($raw, function ($result, $value) {
  $result [$value] = $value; return

  $result;
}, []);
[1 => 1, 2 => 2, ... 5 => 5]

Only one or more parameters are accepted in the 6.array_map closure, the number of parameters of the closure and the number of parameters of the Array_map itself must be the same

$input = [' key ' => ' value '];
Array_map (function ($key, $value) {

  echo $key. $value;
}, Array_keys ($input), $input)
//' keyvalue '
$double = function ($item) {return
 2 * $item;
}

$result = Array_map ($double, [1,2,3]);

2 4 6

7. Breeding Rabbits

$month =;
  $fab = Array ();

  $fab [0] = 1;
  $fab [1] = 1;

   for ($i = 2; $i < $month; $i + +)
   {
     $fab [$i] = $fab [$i-1] + $fab [$i-2];
   }

   for ($i = 0; $i < $month; $i + +)
   {
     echo sprintf ("{%d} month rabbit is: {%d}", $i, $fab [$i]). " <br/> ";
   }

8. DateTime

function Getcurmonthfirstday ($date)
{return
  date (' y-m-01 ', Strtotime ($date));
}
 Getcurmonthlastday (' 2015-07-23 ')
function Getcurmonthlastday ($date)
{return
  date (' y-m-d ', Strtotime date (' y-m-01 ', Strtotime ($date)). ' +1 month-1 Day ');
}

9. Encrypt and decrypt

function Encrypt ($data, $key) {$key = MD5 ($key);
  $x = 0;
  $len = strlen ($data);
  $l = strlen ($key);
  $char = ';
    for ($i = 0; $i < $len; $i + +) {if ($x = = $l) {$x = 0;
    $char. = $key {$x};
  $x + +;
  } $str = ';
  for ($i = 0; $i < $len; $i + +) {$str. = Chr (Ord ($data {$i}) + (Ord ($char {$i}))% 256);
Return Base64_encode ($STR);
  function Decrypt ($data, $key) {$key = MD5 ($key);
  $x = 0;
  $data = Base64_decode ($data);
  $len = strlen ($data);
  $l = strlen ($key);
  $char = ';
    for ($i = 0; $i < $len; $i + +) {if ($x = = $l) {$x = 0;
    $char. = substr ($key, $x, 1);
  $x + +;
  } $str = ';  for ($i = 0; $i < $len; $i + +) {if Ord (substr ($data, $i, 1)) < Ord (substr ($char, $i, 1)) {$str. =
    Chr (Ord (substr ($data, $i, 1)) + 256)-Ord (substr ($char, $i, 1)));
    else {$str. = Chr (Ord (substr ($data, $i, 1))-Ord (substr ($char, $i, 1));
  }
  }return $str;

 }

10. Multidimensional Array demotion

function Array_flatten ($arr) {$result = [];
  Array_walk_recursive ($arr, function ($value) use (& $result) {$result [] = $value;

  });
return $result; } print_r (Array_flatten ([1,[2,3],[4,5]))//[1,[2,3],[4,5]] => [1,2,3,4,5]//var New_array = Old_array.concat ( value1[, value2[, ...
[, Valuen]]]
var test = [1,2,3,[4,5,6],[7,8]]; [].concat.apply ([], test); [1,2,3,4,5,6,7,8] concat it into an empty array [] for each value in the test array, and because Concat is the prototype of the array, we use an empty array as the carrier Var tes

T1 = [1,2,[3,[4,[5]]]]; function Flatten (arr) {return arr.reduce (function (pre, cur) {if (Array.isarray (cur)) {return Flatten (Pre.con
    Cat (cur));
  return Pre.concat (cur);
}, []); }//[1,2,3,4,5] json_encode Chinese function json_encode_wrapper ($result) {if (Defined (' Json_unescaped_unicode ')) {Retu RN Json_encode ($result, json_unescaped_unicode|
  Json_numeric_check);
}else {return preg_replace ("#\\\u ([0-9a-f][0-9a-f][0-9a-f][0-9a-f]) #ie", "/\" (\d+) \ "/",),      Array ("Iconv" (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' \\1 ')) "," \\1 "), Json_encode ($result));

 }
}

12. Two-d array to heavy

 $arr = Array (array (' ID ' => ' 2 '), ' title ' => ' ... ', ' ding ' => ' 1 ', ' Jing ' => ' 1 ', ' Time ' => ' ... ', ' url ' => ' ... ', ' DJ ' => ' ... '), array (' ID ' => ' 2 ', ' title ' => ' ... ', ' ding ' => ' 1 ', ' jing ' =
> ' 1 ', ' time ' => ' ... ', ' url ' => ' ... ', ' DJ ' => ' ... '); function About_unique ($arr =array ()) {/* is the two-dimensional array as a one-dimensional array, then the value value of the one-dimensional array is the same, the kill leaves only one, and the one-dimensional array is returned with the rearrangement indexed array, and each element in the returned one-dimensional array
  is an associative array of the original key value * * * $keys =array ();
  $temp = Array ();
  foreach ($arr [0] as $k => $arrays) {///* The key value of the associative array under record/* =/$keys [] = $k;  }//return $keys;
  /* Descending dimension/foreach ($arr as $k => $v) {$v = join (",", $v);//Descending dimension $temp [] = $v; } $temp = Array_unique ($temp); 
  Remove duplicate content foreach ($temp as $k => $v) {/* re-assemble the disassembled array by index array * * $temp [$k] = Explode (",", $v);  }//return $temp; /* The disassembled array is reassembled by associative array key value/foreach ($temp as $k => $v) {foreach ($v as $kkk => $ck) {$data [$k] [$keys [$kkk]] = $temp [$k]
  [$KKK];
 } return $data; }

13. Format Byte size

/**
* Format byte size
* @param   number $size bytes
* @param string $delimiter number and unit separator
* @return string      Formatted size with unit
* @author
/function Format_bytes ($size, $delimiter = ') {
 $units = array (' B ', ' KB ', ' MB ') , ' GB ', ' TB ', ' PB ');
 for ($i = 0; $size >= 1024 && $i < 6; $i + +) $size/= 1024;
 Return round ($size, 2). $delimiter. $units [$i];
}

14.3 minutes ago.

/**
* Converts the specified timestamp to the format that is before the current XX time such as return ' 3 minutes ago '
@param string|int $timestamp unix Timestamp
* @return String
* /
function Time_ago ($timestamp) {
  $etime = time ()-$timestamp;
  if ($etime < 1) return ' just ';   
  $interval = Array (* *     
   => ' (' y-m-d ', $timestamp) (') ') ', * * * *    =&G T ' A month ago ('. Date (' m-d ', $timestamp). ') ',
   7 *    => ' Week ('. Date (' m-d ', $timestamp). ') ',
   24 * 60 * 6 0      => ' days ago ',         => ' hours ago ',           => ' minutes ago ',
   1            => ' seconds ago '
  );
  foreach ($interval as $secs => $str) {
    $d = $etime/$secs;
    if ($d >= 1) {
      $r = round ($d);
      Return $r. $str;}}
  ;

15. ID Number

/** * Determine if the parameter string is a celestial ID number * @param $id a string or number that needs to be judged * @return mixed false or array[the content array Boolean is true]/function is_citize
  N_ID ($id) {//The length of the 18-digit ID is uppercase $id = Strtoupper ($id); if (!) ( Preg_match ('/^\d{17} (\d| X) $/', $id) | |
  Preg_match ('/^\d{15}$/', $id))) {return false; 
  }///15 digits converted to 18 bits and converted to string $Wi = Array (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8); 
  $Ai = Array (' 1 ', ' 0 ', ' X ', ' 9 ', ' 8 ', ' 7 ', ' 6 ', ' 5 ', ' 4 ', ' 3 ', ' 2 ');
  $cardNoSum = 0; if (strlen ($id) ==16) {$id = substr (0, 6). ' 
    SUBSTR (6, 9);
    for ($i = 0; $i < $i + +) {$cardNoSum + + substr ($id, $i, 1) * $Wi [$i]; 
    $seq = $cardNoSum% 11;
  $id = $id. $Ai [$SEQ];
  The validity of the last character of the 18-digit ID card $cardNoSum = 0;
  $id = substr ($id, 0,17);
  $lastString = substr ($id, 17, 1);
  for ($i = 0; $i < $i + +) {$cardNoSum + + substr ($id, $i, 1) * $Wi [$i];
  $seq = $cardNoSum% 11;
  $realString = $Ai [$seq];
  if ($lastString!= $realString) {return false;} ToDomain Efficacy $oCity = array (11=> "Beijing",12=> "Tianjin",13=> "Hebei",14=> "Shanxi",15=> "Inner Mongolia",21=> "Liaoning",22=> "Jilin",23=> " Heilongjiang ",31=>" "Shanghai",32=> "Jiangsu",33=> "Zhejiang",34=> "Anhui",35=> "Fujian",36=> "Jiangxi",37=> "Shandong",41=> "Henan",42=> " Hubei ",43=>" Hunan ",44=>" Guangdong ",45=>" Guangxi ",46=>" Hainan ",50=>" Chongqing ",51=>" Sichuan ",52=>" Guizhou ",53=>" Yunnan ",54=>" Tibet ",61=>" Shaanxi ",62=>" Gansu ",63=>" Qinghai ",64=>" Ningxia ",65=>" Xinjiang ",71=>" Taiwan ",81=>" Hong Kong ",82=>" Macao ",91=>" foreign ")
  ;
  $City = substr ($id, 0, 2);
  $BirthYear = substr ($id, 6, 4);
  $BirthMonth = substr ($id, 10, 2);
  $BirthDay = substr ($id, 12, 2); $Sex = substr ($id, 16,1)% 2//male 1 female 0//$SEXCN = $Sex? '
  Male ': ' Female ';
  The Domain Verification if (is_null ($oCity [$City])) {return false;}
  Date of birth, if ($BirthYear >2078 | | $BirthYear <1900) {return false;}
  $RealDate = Strtotime ($BirthYear. '-$BirthMonth. '-'. $BirthDay); if (date (' Y ', $RealDate)!= $BirthYear | | date (' m ', $RealDate)!= $BirthMonth | | date (' d ', $RealDate)!= $BirthDay) {return FA
  Lse Return arrAY (' id ' => $id, ' location ' => $oCity [$City], ' Y ' => $BirthYear, ' m ' => $BirthMonth, ' d ' => $BirthDay, ' sex ' =
> $Sex);
 }

16. Gets the collection of a key in a two-dimensional array

$user = Array (0 => array (' ID ' => 1, ' name ' => ' John ', ' email ' => ' zhangsan@sina.com '), 1 => array (' id ' = > 2, ' name ' => ' Dick ', ' email ' => ' lisi@163.com ', 2 => array (' ID ' => 5, ' name ' => ' Harry ', ' email ' => ' 10000@qq.com ',), ...);
$ids = Array (); $ids = Array_map (' Array_shift ', $user);
$ids = Array_column ($user, ' id ');//php5.5
$names = Array (); $names = Array_reduce ($user, Create_function (' $v, $w ', ' $ v[$w ["id"]]= $w ["name"];return $v; ')];

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.