【php随笔】一些小方法

一、获取一个二维数组的某个键的最大值

/**
 * @param $arr  (二维数组)
 * @param $field  (索引)
 * @return bool|mixed
 */
function searchMax($arr, $field){
     //判断是否是数组以及传过来的字段是否是空
     if (!is_array($arr) || !$field) {
         return false;
     }
     $temp = array();
     foreach ($arr as $key => $val) {
         $temp[] = $val[$field]; // 用一个空数组来承接字段
     }
     return max($temp);
 }

二、二维数组去重

/**
 * @param $arr (要去重的数组)
 * @param $key (去重的字段)
 * @return mixed
 */
function assoc_unique($arr, $key){
   $tmp_arr = array();
   foreach ($arr as $k => $v) {
       if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回true
           unset($arr[$k]);
       } else {
           $tmp_arr[] = $v[$key];
       }
   }
   return $arr;
}

三、二维数组按某个键排序

$data = [
   ['name' => '张三','age' => 18],
   ['name' => '李四','age' => 40],
   ['name' => '王五','age' => 35],
   ['name' => '赵六','age' => 8],
   ['name' => '郑七','age' => 20],
];

$last_names = array_column($data, 'age');
//默认SORT_ASC从小到大,SORT_DESC从大倒小
array_multisort($last_names, SORT_DESC, $data);

结果
在这里插入图片描述
四、curl发送http请求

/**
 * @param  string $url 请求URL
 * @param  array $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function http_get_post($url, $params, $method = 'GET', $header = array(), $multi = false)
{
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header
    );
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式!');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) throw new Exception('请求发生错误:' . $error);
    return $data;
}

function https_request($url, $data = null)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	if (!empty($data)) {
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}

五、curl发送post请求json数据

/**
 * @param $url 请求url
 * @param $data 请求数据(数组)
 * @return array|mixed
 */
function http_post_json($url, $data)
{
    $data = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $header = empty($header) ? ['Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($data)] : $header;
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    $error = curl_errno($ch);
    if ($error) return ['errorno' => false, 'errmsg' => $error];
    curl_close($ch);
    return json_decode($result, true);
}

六、二维数组按照某键值去重,另一个value值相加

$list = array(
	['name' => '张三','money' => '200'],
	['name' => '李四','money' => '500'],
	['name' => '张三','money' => '100'],
	['name' => '王五','money' => '300'],
	['name' => '赵六','money' => '400'],
);

$item = [];
foreach ($list as $k => $v) {
	if (!isset($item[$v['name']])) {
		$item[$v['name']] = $v;
	} else {
		$item[$v['name']]['money'] += $v['money'];
	}
}
$list = array_values($item);

七、无限极分类
①不使用递归方法:

$data = [
	[
		'id' => 1,
		'name' => 'PHP',
		'pid' => 0,
		'path' => '0'
	],
	[
		'id' => 2,
		'name' => '数据库',
		'pid' => 0,
		'path' => '0'
	],
	[
		'id' => 3,
		'name' => 'web前端',
		'pid' => 0,
		'path' => '0'
	],
	[
		'id' => 4,
		'name' => 'thinkPHP',
		'pid' => 1,
		'path' => '0-1'
	],
	[
		'id' => 5,
		'name' => 'yii',
		'pid' => 1,
		'path' => '0-1'
	],
	[
		'id' => 6,
		'name' => 'yii2.0',
		'pid' => 5,
		'path' => '0-1-5'
	],
];
foreach ($data as &$row) {
	//计算path的-数量
	$num = substr_count($row['path'], '-');
	if ($num > 0) {
		$row['all'] = '|' . str_repeat('—',$num) . $row['name'];
	} else {
		$row['all'] = $row['name'];
	}
	$arr[] = str_replace('-', '', $row['path'] . '-' . $row['id']);
}
array_multisort($arr,SORT_STRING,$data);
var_dump($data);
foreach ($data as $rows) {
	echo "<p>{$rows['all']}</p>";
}

效果:
在这里插入图片描述

八、索引数组变成关联数组

$keyArr = ['name','age','gender'];

$valueArr = ['张三',18,'男'];

$result = array_combine($keyArr,$valueArr);

var_dump($result);

结果:
在这里插入图片描述
九、XML数据转成数组

function xmlToArray($xml) {
   libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

十、无限极数据处理方法

/**
 * 一维数组生成数据树
 * @param mixed $list 数据列表
 * @param string $id 父ID Key
 * @param string $pid ID Key
 * @param string $son 定义子数据Key
 * @return array
 */
function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
{
    $tree = $map = [];
    foreach ($list as $item) {
        $map[$item[$id]] = $item;
    }
    foreach ($list as $item) {
        if (isset($item[$pid]) && isset($map[$item[$pid]])) {
            $map[$item[$pid]][$son][] = &$map[$item[$id]];
        } else {
            $tree[] = &$map[$item[$id]];
        }
    }
    unset($map);
    return $tree;
}

/**
 * 二维数组生成数据树
 * @param $list
 * @param string $id
 * @param string $pid
 * @param string $path
 * @param string $ppath
 * @return array
 */
function arr2table($list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
 {
     $_array_tree = arr2tree($list, $id, $pid);
     $tree = [];
     foreach ($_array_tree as $_tree) {
         $_tree[$path] = $ppath . '-' . $_tree[$id];
         $grade = intval(count(explode('-', $_tree[$path])) - 1);
         $count = intval(substr_count($ppath, '-'));
         if ($count < 2) {
             $_tree['spl'] = str_repeat('&nbsp;├─ ', $count);
         } else {
             $_tree['spl'] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', ($count - 1)) . '├─ ';
         }
         $_tree['grade'] = ($grade <= 1) ? 1 : $grade;
         if (!isset($_tree['sub'])) $_tree['sub'] = [];
         $sub = $_tree['sub'];
         unset($_tree['sub']);
         $tree[] = $_tree;
         if (!empty($sub)) {
             $sub_array = arr2table($sub, $id, $pid, $path, $_tree[$path]);
             $tree = array_merge($tree, (Array)$sub_array);
         }
     }
     return $tree;
}

十一、Nginx配置伪静态

if (!-e $request_filename) {
   rewrite  ^(.*)$  /index.php?s=/$1  last;
   break;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值