## php常用自定义实用方法(第一节)
## *电商开发、微信支付宝开发常用*
> 1、int数字加密解密,根据时间戳将指定int生成随机字符
```php
/**
* @param int $num
* @return $this
* 数字加密
*/
function encode_num($num = 0)
{
$num_len = strlen($num);
if (!is_numeric($num) || $num_len > 15) {
$this->data = false;
$this->message = '请输入数字';
return $this;
}
list($start_rand, $end_rand, $nums, $pies) = [rand(100, 999), rand(10, 99), [], self::unique_rand(1, 9, 9)];
for ($i = 0; $i < ($num_len / 2); $i++) {
$nums[$pies[$i]] = ['num' => substr($num, $i * 2, 2), 'rand' => rand(1000, 7000), 'pie' => $pies[$i], 'i' => $i + 1];
}
ksort($nums);
$str = $start_rand;
foreach ($nums as $maps) {
list($rand, $d_rand) = [rand(10, 70), rand(1, 9)];
$i = $rand + $maps['i'] + $d_rand;
$len=strlen($maps['num']);
$vs = ($maps['num'] * $maps['pie']) + $maps['rand'] + $start_rand - ($end_rand * $maps['i']) + $i;
$str .= $maps['rand'] . $maps['pie'] . $rand . $i . $d_rand .$len .$vs;
}
return $str . $end_rand;
}
/**
* @param int $num
* @return $this
* 数字解密
*/
function decode_num($num = 0)
{
if (!is_numeric($num)) {
return false;
}
if (empty($num)) $num = $this->data;
list($start_rand, $end_rand, $num_len, $encode, $nums) = [ceil(substr($num, 0, 3)), ceil(substr($num, -2)), ceil(strlen($num) - 5), substr(substr($num, 3), 0, -2), []];
for ($i = 0; $i < ceil($num_len / 15); $i++) {
$nums[] = substr($encode, $i * 15, 15);
}
$n = [];
foreach ($nums as $maps) {
list($maps_rand, $pie, $rand, $i, $d_rand, $vs,$len) = [ceil(substr($maps, 0, 4)), ceil(substr($maps, 4, 1)), substr($maps, 5, 2), intval(substr($maps, 7, 2)), substr($maps, 9, 1), ceil(substr($maps, 11)),ceil(substr($maps,10,1))];
$rule_i = intval($i - $rand - $d_rand);
$v = ceil(($vs - $i + ($end_rand * $rule_i) - $start_rand - $maps_rand) / $pie);
if($len==2 && strlen($v)==1) $v='0'.$v;
$n[$rule_i] = $v;
}
ksort($n);
return implode($n, '');
}
```
> 2、生成一定数量的不重复的随机数
```php
/**
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
function unique_rand($min, $max, $num)
{
$count = 0;
$return = array();
while ($count < $num) {
$return[] = mt_rand($min, $max);
$return = array_flip(array_flip($return));
$count = count($return);
}
shuffle($return);
return $return;
}
```
> 3、驼峰和下滑线转换方法
```php
/**
* @param $data
* @return mixed
* 下滑线转驼峰
*/
public static function convert2Underline($data)
{
$data = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
return strtoupper($matches[2]);
}, $data);
return $data;
}
/**
* 驼峰转下划线
* @param $data
* @return mixed
*/
public function hump2ToLine($data)
{
$data = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
return '_' . strtolower($matches[0]);
}, $data);
return $data;
}
```
> 4、获取汉字/英文首字母
```php
/**
* @param $data
* @return string
* 获取汉字/英文首字母
*/
function Str2First($data)
{
$data = iconv("UTF-8", "gb2312", $data);//编码转换
if (preg_match("/^[\x7f-\xff]/", $data)) {
$fchar = ord($data{0});
if ($fchar >= ord("A") and $fchar <= ord("z")) return strtoupper($data{0});
$a = $data;
$val = ord($a{0}) * 256 + ord($a{1}) - 65536;
if ($val >= -20319 and $val <= -20284) return "A";
if ($val >= -20283 and $val <= -19776) return "B";
if ($val >= -19775 and $val <= -19219) return "C";
if ($val >= -19218 and $val <= -18711) return "D";
if ($val >= -18710 and $val <= -18527) return "E";
if ($val >= -18526 and $val <= -18240) return "F";
if ($val >= -18239 and $val <= -17923) return "G";
if ($val >= -17922 and $val <= -17418) return "H";
if ($val >= -17417 and $val <= -16475) return "J";
if ($val >= -16474 and $val <= -16213) return "K";
if ($val >= -16212 and $val <= -15641) return "L";
if ($val >= -15640 and $val <= -15166) return "M";
if ($val >= -15165 and $val <= -14923) return "N";
if ($val >= -14922 and $val <= -14915) return "O";
if ($val >= -14914 and $val <= -14631) return "P";
if ($val >= -14630 and $val <= -14150) return "Q";
if ($val >= -14149 and $val <= -14091) return "R";
if ($val >= -14090 and $val <= -13319) return "S";
if ($val >= -13318 and $val <= -12839) return "T";
if ($val >= -12838 and $val <= -12557) return "W";
if ($val >= -12556 and $val <= -11848) return "X";
if ($val >= -11847 and $val <= -11056) return "Y";
if ($val >= -11055 and $val <= -10247) return "Z";
} else {
return '#';
}
}
```
> 5、生成随机订单号
```php
/**
* @param int $digits /单号位数
* @param string $prefix /单号长度
* @return string
* 创建随机单号
*/
public function create_order_number($digits = 24, $prefix = '')
{
$date = date('YmdHis');
$digits = intval($digits);
if ($digits < 14) return '随机单号大于14字符';
$digits = $digits - strlen($date) - strlen($prefix);
if ($digits < 0) return '随机单号生成失败';
$rand = '';
$num = floor($digits / 10);
for ($i = 0; $i < $num; $i++) {
$rand .= str_pad(mt_rand(1, (int)9999999999), 10, '0', STR_PAD_LEFT);
}
if ($digits % 10 != 0) {
$rand .= str_pad(mt_rand(1, (int)substr(9999999999, 0, $digits - ($num * 10))), $digits - ($num * 10), '0', STR_PAD_LEFT);
}
$order_number = $prefix . $date . $rand;
return $order_number;
}
```
> 6、字符串的截取
```php
/**
* @param $string /要截取的字符串
* @param $start /开始字符
* @param $end /结束字符
* @return string
* 截取两个字符串之间的数据
*/
public function get_string_between($string, $start, $end=null)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = is_null($end)?strlen($string)-$ini:strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
```
> 7、只替换第一个字符
```php
/**
* @param $needle 搜索字符
* @param $replace 替换的字符
* @param $haystack 要替换字符
* @return mixed
* 只替换一次字符
*/
public function str_replace_once($needle, $replace, $haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
```
> 8、随机字符
```php
/**
* @param int $length 字符长度
* @param $type 1 数字+字母 2数字 3 数字+字母+字符 4字母
* @return string
* 随机字符
*/
public function create_number($length = 6, int $type = 1)
{
$chars = [
1 => '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
2 => '0123456789',
3 => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|',
4 => 'abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
];
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[$type][mt_rand(0, strlen($chars[$type]) - 1)];
}
return $str;
}
```
> 9、数组分页
```php
/**
* @param $data
* @param int $page_num
* @param null $page
* @return array
* 数组分页
*/
public function array_page(array $data, $page_num = 15, $page = null)
{
if (is_null($page)) $page = $_REQUEST['page'];
empty($page) ? $page = 1 : true;
$data = array_slice($data, ($page - 1) * $page_num, $page_num);
$total = count($data);
return ['total' => $total, 'per_page' => $page_num, 'current_page' => $page, 'last_page' => ceil($total / $page_num), 'data' => $data];
}
```
> 10、数组转XML/XML转数组/json转数组/数组转json
```php
/**
* @param $data /要转换的数据
* @param null $partition 字符串炸开数组分隔符
* @return array|mixed|string
* 转数组
*/
public function toArray($data, $partition = null)
{
$data_type = self::getDataType($data);
if ($data_type == 'array') return $data;
if ($data_type == 'json') return self::json2array($data);
if ($data_type == 'xml') return self::xml2array($data);
if (!is_null($partition) && $data_type == 'string') return explode($partition, $data);
if ($data_type = 'object') return self::object2array($data);
$this->message = '数据格式不正确转换出错';
return $data;
}
/**
* @param $data /要转的数据
* @return array|mixed|string
* 转json
*/
public function toJson($data)
{
$data_type = self::getDataType($data);
if ($data_type == 'json') return $data;
$data = self::toArray($data);
if (is_array($data)) {
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function ($matches) {
return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");
}, ($jsonData = json_encode($data)) == '[]' ? '{}' : $jsonData);
} else {
$this->message = '数据格式不正确转换出错';
return $data;
}
}
/**
* @param $data /要转的数据
* @return array|mixed|string
* 转xml
*/
public function toXml($data)
{
$data_type = self::getDataType($data);
if ($data_type == 'xml') return $data;
$data = self::toArray($data);
if (is_array($data)) {
return "<xml>" . self::arr2xml($data) . "</xml>";
} else {
$this->message = '数据格式不正确转换出错';
return $data;
}
}
/**
* XML内容生成
* @param array $data 数据
* @param string $content
* @return string
*/
private static function arr2xml($data, $content = '')
{
foreach ($data as $key => $val) {
is_numeric($key) && $key = 'item';
$content .= "<{$key}>";
if (is_array($val) || is_object($val)) {
$content .= self::arr2xml($val);
} elseif (is_string($val)) {
$content .= '<![CDATA[' . preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $val) . ']]>';
} else {
$content .= $val;
}
$content .= "</{$key}>";
}
return $content;
}
/**
* @param $data
* 获取数据类型
*/
public function getDataType($data)
{
$type = gettype($data);
if ($type == 'string') {
if ($this->json_check($data)) $type = 'json';
if ($this->xml_check($data)) $type = 'xml';
}
return $type;
}
/**
* @param $data /xml数据
* @return mixed
* xml转数组
*/
public function xml2array($data)
{
$entity = libxml_disable_entity_loader(true);
$data = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
libxml_disable_entity_loader($entity);
return json_decode(self::toJson($data), true);
}
/**
* @param $data /json数据
* @return mixed
* @throws \Exception
* json转数组
*/
public function json2array($data)
{
$result = json_decode($data, true);
if (empty($result)) {
throw new \Exception('invalid response.', '0');
}
return $result;
}
/**
* @param $data
* @return bool
* 检测是否为json数据
*/
public function json_check($data)
{
if (!is_null(json_decode($data))) {
return true;
} else {
return false;
}
}
/**
* @param $data
* @return bool|mixed
* 检测是否为xml数据
*/
public function xml_check($data)
{
$xml_parser = xml_parser_create();
if (!xml_parse($xml_parser, $data, true)) {
xml_parser_free($xml_parser);
return false;
} else {
return (json_decode(json_encode(simplexml_load_string($data)), true));
}
}
```
> 11、数字四舍五入,向上,向下,保留小数方法
```php
/**
* @param $data /要转换的数字
* @param int $place /保留几位小数
* @param int $type /1四舍五入 2向下取 3向上取
* @return float|int
* 数字转换
*/
public function toNumber($data, int $place = 2, int $type = 1)
{
if (is_numeric($data) === false) return $data;
if ($place == 0 && $type == 1) return (int)round($data);
if ($place == 0 && $type == 2) return (int)floor($data);
if ($place == 0 && $type == 3) return (int)ceil($data);
if ($type == 1) return (float)sprintf("%.{$place}f", substr(sprintf("%." . ($place * 2) . "f", $data), 0, -2));
if ($type == 2) return (float)sprintf("%.{$place}f", substr(sprintf("%." . ($place + 2) . "f", $data), 0, -2));
if ($type == 3) return (float)sprintf("%.{$place}f", substr(sprintf("%." . ($place + 2) . "f", $data), 0, -2)) + (1 / (pow(10, $place)));
return $data;
}
```