PHP常用函数总结


常用关键字:JSON_UNESCAPED_UNICODE

一、数组函数

(1)array_group_by

该函数需要自己添加到项目中

/**
 * [array_group_by 数组分组]
 * @param  [type] $arr [二维数组]
 * @param  [type] $key [键名]
 * @return [type]      [新的二维数组]
 */
function array_group_by($arr, $key){
    $grouped = array();
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $parms = array_merge($value, array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}
$list = array_group_by($list,'parent_id'); //根据父级ID分组
$list1 = $list[1]; //直接获取到父级ID为1的数据

$list1 = array_group_by($list,'id')[1][0];

(2)array_column

$typelist = []; //获取数据库中的全部数据
$types = array_column($typelist,'name','id'); //把数据做成键值对
$name1 = $types[1]; //获取到id=1的记录对应的name值
$typelist = []; //获取数据库中的全部数据
$types = array_column($typelist,'name'); //把数据做成数组

(3)array_multisort

array_multisort(
    array_column($list,'age'),SORT_DESC,
    array_column($list,'number'),SORT_DESC,
    array_column($list,'id'),SORT_ASC,
    $list
);

(4)array_chunk

$list = []; //获取数据库中的全部数据
$limit = 100;
$page = 2; //查询数据的页码
$lists = array_chunk($list,$limit); //根据每100条分组
$pagelist = $lists[$page - 1] ?? []; //查询对应页码的数据
return $pagelist;

(5)array_splice

$list = []; //获取数据库中的全部数据
$list = array_splice($list,0,5); //取前面5条
$a = ["red","green","blue","yellow","brown"];
$b = array_slice($a,2);
$b = ["blue","yellow","brown"];

(6)array_sum

$list = []; //获取数据库中的全部数据
$total = array_sum(array_column($list,'money')); // 汇总列表的money

(7)array_key_exists

$typelist = []; //获取数据库中的全部数据
$types = array_column($typelist,'name','phone'); //把数据做成键值对
$phone = "13000001111";
if(array_key_exists($phone,$types)){
    echo "查到手机号的姓名为:".$types[$phone];
}

二、字符串函数

(1)拆分数组

$str = "100,101,102,103,104,105,106";
$nums = explode(',',$str);
//$nums[0] == 100;

$nums = [100,101,102,103,104,105,106];
$str = implode(',',$nums);
// $str = "100,101,102,103,104,105,106";

(2)截取字符串

$string = "0123456789";
$str0 = substr($string,0,3);
// $str0 = "012";

(3)包含字符串

$string = "0123456789";
if(strstr($string,"789")){
    echo "true";
}

(4)替换字符串

$string = str_replace('php','java',$string); //把$string中的php换成java

(5)html标签替换

$text = html_entity_decode($html); //解析 等html标签

三、JSON函数

(1)json和字符串转换

$list = []; //从数据库中查询
$string = json_encode($list,JSON_UNESCAPED_UNICODE); //数组转为json字符串(中文不乱码)
$list = json_decode($string,true); //json字符串转为数组

四、IP地址函数

(1)IPv4与数字转换

ip2long("127.0.0.1");       //2130706433
ip2long("255.255.255.255"); //4294967295
long2ip(1);                 //0.0.0.1

(2)IPv6与数字转换

$ip = '2409:8a6a:822f:a40:3060:3060:3060:3060';
$nip = inet_pton($ip);
bin2hex($nip); //24098a6a822f0a403060306030603060

(3)获取用户真实IP

/**
 * [ip 获取用户IP(ThinkPHP自带的函数有问题,所以自己写一个)20240622]
 * @access public
 * @param  integer   $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param  boolean   $adv 是否进行高级模式获取(有可能被伪装)
 * @param  string    $httpAgentIpHeader 获取代理IP的头部
 * @return [string]      [新的IP地址]
 */
function get_client_ip($type = 0, $adv = true, $httpAgentIpHeader = ''){
    $type      = $type ? 1 : 0;
    static $ip = null;

    if (null !== $ip) {
        return $ip[$type];
    }

    $httpAgentIp = $httpAgentIpHeader;
    
    $server = $_SERVER;

    if ($adv) {
        if ($httpAgentIp && isset($server[$httpAgentIp])) {
            $ip = $server[$httpAgentIp];
        }elseif (isset($server['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $server['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($server['HTTP_CLIENT_IP'])) {
            $ip = $server['HTTP_CLIENT_IP'];
        } elseif (isset($server['REMOTE_ADDR'])) {
            $ip = $server['REMOTE_ADDR'];
        }
    } elseif (isset($server['REMOTE_ADDR'])) {
        $ip = $server['REMOTE_ADDR'];
    }

    // IP地址类型
    $ip_mode = (strpos($ip, ':') === false) ? 'ipv4' : 'ipv6';

    // IP地址合法验证
    if (filter_var($ip, FILTER_VALIDATE_IP) !== $ip) {
        $ip = ('ipv4' === $ip_mode) ? '0.0.0.0' : '::';
    }

    // 如果是ipv4地址,则直接使用ip2long返回int类型ip;如果是ipv6地址,暂时不支持,直接返回0
    $long_ip = ('ipv4' === $ip_mode) ? sprintf("%u", ip2long($ip)) : 0;

    $ip = [$ip, $long_ip];

    return $ip[$type];
}