Home » Code » PHP拾零

PHP拾零

生成不重复随机数

function distinct_int($num, $min = 1, $max = 10000) {
    $count = 0;
    $result = array();
    while ($count < $num) {
        $result[] = mt_rand($min, $max);
        $result = array_flip(array_flip($result));
        $count = count($result);
    }
    return $result;
}

获得客户端IP

function get_client_ip() {
	$client_ip = '';
	$client_ip_list = '';
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		$client_ip_list = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	elseif (!empty($_SERVER['HTTP_X_REAL_IP']))
	{
		$client_ip_list = $_SERVER['HTTP_X_REAL_IP'];
	}
	elseif (!empty($_SERVER['HTTP_PROXY_FORWARDED_FOR']))
	{
		$client_ip_list = $_SERVER['HTTP_PROXY_FORWARDED_FOR'];
	}
	if (strpos($client_ip_list, ',') !== false)
	{
		$client_ip = strstr($client_ip_list, ',', true);
	}
	else
	{
		$client_ip = $client_ip_list;
	}
	if (empty($client_ip))
	{
		$client_ip = empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR'];
	}
	return $client_ip;
}

判断正则表达式是否合法

有时候需要判断一个正则表达式是否合法,可以让它跟null来进行匹配:preg_match($regularString, null),如果结果 === false,则$regularString是有问题的,否则是无问题的。如果有问题会有错误报出,可以考虑在前边加上@符号。不要想着用正则去判断正则,没有必要也是浪费时间!参见这里

validate_regular

二维数组排序

$scores = [
  ['type' => 1, 'value' => 10],
  ['type' => 1, 'value' => 20],
  ['type' => 3, 'value' => 50],
  ['type' => 4, 'value' => 80],
  ['type' => 2, 'value' => 50],
  ['type' => 4, 'value' => 50],
  ['type' => 4, 'value' => 60],
  ['type' => 3, 'value' => 160],
];

//需求:按type排序,先后顺序为4, 3, 1, 2

//方案1
$typeSort = [];
foreach ($scores as $key => $value)
{
  switch ($value['type']) {
    case 4:
      $weight = 1;
      break;
    case 3:
      $weight = 2;
      break;
    case 1:
      $weight = 3;
      break;
    case 2:
      $weight = 4;
      break;
  }
  $typeSort[$key] = $weight;
}

array_multisort($typeSort, SORT_ASC, $scores);
var_dump($scores);

//方案2:
function uTypeSort($a, $b) {
  static $map = [
    4 => 1,
    3 => 2,
    1 => 3,
    2 => 4,
  ];

  if ($map[$a['type']] == $map[$b['type']])
  {
    return 0;
  }
  return $map[$a['type']] > $map[$b['type']] ? 1 : -1;
}

usort($scores, 'uTypeSort');
var_dump($scores);

个人感觉方案1更好一些,这里涉及字段权重的概念。

从数组中按键截取部分

比如原始数组:[‘a’ => ‘张三’, ‘b’ => ‘李四’, ‘c’ => ‘王五’];传递[‘a’, ‘c’]返回张三和王五。

$r = array_intersect_key($array, array_flip((array)$keys));

输出前导0及保留小数位数

//可以使用sprintf
echo sprintf('%03d', 1);//001
echo sprintf('%.3f', 25.78914);//25.789

命令空间use

use不一定要到具体类名,可以只use其中一部分,只是使用的时候要“接得上来”。

namespace A\B\C\D;

class E
{

}

namespace AA;

use A\B\C\D;
use A\B\C;

$e1 = new D\E; //不能少写成new E;
$e2 = new C\D\E; //也不能多写成new B\C\D\E

var_dump($e1, $e2); 
//输出:object(A\B\C\D\E)#1 (0) { } object(A\B\C\D\E)#2 (0) { }

One comment

  1. 文章内容好像对不起标题啊,哈哈

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Time limit is exhausted. Please reload CAPTCHA.