php 笔记

得到二维数据中指定列值
array_column

数组去重
array_unique

array_merge($info);//重新排列数组下标

mysql时间设置默认值
1、将字段类型设为 TIMESTAMP
2、将默认值设为 CURRENT_TIMESTAMP

js防止链接跳转
event.preventDefault();

获取指定日期的星期:

$weekarray=array("日","一","二","三","四","五","六");
echo "星期".$weekarray[date("w",strtotime("2011-11-11"))];

MySql字段含有逗号,根据逗号分隔的数据查询
数据库数据(只查询含有75的数据,但是要排除掉751和752)
SELECT * FROM test WHERE FIND_IN_SET(‘75’,name)

//生成树状结构
function generateTree2($rows, $id='id', $pid='reid'){
    $items = array();
    foreach ($rows as $row) $items[$row[$id]] = $row;
    foreach ($items as $item) $items[$item[$pid]]['son'][$item[$id]] = &$items[$item[$id]];
    return isset($items[0]['son']) ? $items[0]['son'] : array();
}
//多维数组转二维数组
function imp($tree, $children='son') {
    $imparr = array();
    foreach($tree as $w) {
        if(isset($w[$children])) {
            $t = $w[$children];
            unset($w[$children]);
            $imparr[] = $w;
            if(is_array($t)) $imparr = array_merge($imparr, imp($t, $children));
        } else {
            $imparr[] = $w;
        }
    }
    return $imparr;
}

tp5 按字段分组取最大值记录

 $city=input('city');

 $time1=strtotime(date('Y-m-d'));
 $time2=strtotime('+1 days',$time1);

 $sql='SELECT a.id, a.user_id, a.score, a.school, b.avatar, b.nickname
FROM fa_cfapk_user_question_log AS a
JOIN fa_cfapk_user AS b ON a.user_id=b.id
WHERE score = (SELECT max(score) FROM fa_cfapk_user_question_log WHERE a.user_id = user_id)
AND a.city="'.$city.'" and a.endtime BETWEEN '.$time1.' AND '.$time2.'
GROUP BY user_id
ORDER BY score DESC,id';
 $list=db()->query($sql);

mysql查询数据时,按照时间分组求和

SELECT
	from_unixtime(create_time, "%Y-%m-%d") ctime,
	sum(money) AS money
FROM
	`think_merchant_orderlist`
WHERE
	`create_time` >= 1651568285
AND `status` IN (1, 5)
AND `memberid` = 2
GROUP BY
	`ctime`

php如何以不同系统环境中的回车符来分割字符串?

$str = str_replace(PHP_EOL, "\n",$str);
$arr = array_unique(explode("\n",$str));

分组统计每组数量,当没有结果时返回空数组

$forum_id=implode(',',$forum_id);
$sql="SELECT COALESCE (`forum_id`,'总数') id,COUNT(`id`) nums FROM fa_comment WHERE `forum_id` IN ($forum_id) GROUP BY forum_id WITH ROLLUP";
$arr=db()->query($sql);

php匹配字符串中的中文汉字

 $str='le="max-width: 100%;">在科技不,断。发、展、了;以‘后,我】【!@#¥%……&*()——+=/*-+
《》?“|}{:LPOK恐怕离开,发生sdf 撒大声地阿萨法  防守打法刚发的发生的 sdf 啥地方是对公司的躬逢盛典 sdf 
24px;"></p></div>';
dump($str);
$preg = "/[\x{4e00}-\x{9fa5}]+/u";
if(preg_match_all($preg,$str,$matches)){
    dump($matches);
}

给文章内容随机5%的汉字加拼音

$str='le="max-width: 100%;">在科技不,断。发、展、了;以‘后,我】【!@#¥%……&*(我)——+=/*-+
《》?“|}{:LPOK恐我怕离开,发生sdf 撒大声地我阿萨法  防守打法刚发 的我发生的 sdf 啥地方是对公 我的躬 逢盛典 sdf
24px;"></p>我</div>';
dump($str);
$preg = "/[\x{4e00}-\x{9fa5}]+/u";
$arr=mb_str_split($str);

//给5%的汉字加拼音
$arr2=[];
foreach($arr as $k=>$v){
    if(preg_match_all($preg,$v,$matches)){
        $arr2[$k]=1;
    }
}
//dump($arr2);
if($arr2){
    $n=round(count($arr2)*5/100);//取5%的字
    if($n<=1){
        $n=1;
    }
    $keys=\fast\Random::lottery($arr2,$n);//随机取到的字下标
    if(!is_array($keys)){
        $keys=[$keys];
    }
    foreach($keys as $key){
        $pinyin=\fast\Pinyin::get($arr[$key]);
        $arr[$key]=$arr[$key]."($pinyin)";
    }
}
dump(implode('',$arr));
die;

fastadmin生成Word文件并发送到浏览器

/**
 * 生成Word文档
 * @param $path string 保存位置
 * @param $html string HTML字符串
 */
function createWord($path,$html){
    ob_start();
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:w="urn:schemas-microsoft-com:office:word"
        xmlns="http://www.w3.org/TR/REC-html40">';
    echo $html;
    echo "</html>";
    $data = ob_get_contents();
    ob_end_clean();
    file_put_contents($path,$data);
}
  //下载
    public function download(){
        $id=input('id');
        $row=$this->model->with(['user','course'])->where('results.id',$id)->field('results.*,user.nickname,course.title')->find();
        if(!$row){
            $this->error('记录不存在');
        }
        if(!$row['nr']){
            $this->error('暂无报告');
        }
        $path = $row['nickname'].':【'.$row['title']."】实验报告.doc";
        createWord($path,$row['nr']);

        //发送到浏览器
        \fast\Http::sendToBrowser($path);
    }

js

buttons:[
  {
       name: 'download',
       title: __('下载'),
       text:'下载',
       classname: 'btn btn-xs btn-success btn-click',
       //icon: 'fa fa-pencil',
       url: 'results/download',
       click: function(options, row){
           location.href='results/download?id='+row.id
       },
   },
],

腾讯地图逆地址解析

//地址解析
    public function qqmap(){
        $lat=input('lat');
        $lng=input('lng');
        $r=qqmap($lat,$lng);
        if(!$r['code']){
            $this->error($r['msg']);
        }
        $this->success('ok',$r['city']);
    }
//腾讯地图逆地址解析
function qqmap($lat,$lng){
    $url="https://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key=".config('site.mapkey');
    $ret=\fast\Http::get($url);
    $ret=\GuzzleHttp\json_decode($ret,true);//dump($ret);die;
    if($ret['status']==0){
        return ['code'=>1,'city'=>$ret['result']['ad_info']];
    }else{
        return ['code'=>0,'msg'=>$ret['message']];
    }
}

phpoffice导入时间是数字,转换成时间戳

$v=($v - 25569) * 24 * 3600-28800;

ignore可以实现 插入时不存在则插入,存在则不做插入(根据主键或者唯一索引判断数据是否存在)

$sql=Db('cardno_unique')->fetchSql(true)->insertAll($arr);
$sql=str_replace('INSERT','INSERT ignore',$sql);
$r=db()->execute($sql);

aes 256 cbc加密解密,对接Java的AES/CBC/PKCS5Padding
https://blog.csdn.net/fendouweiqian/article/details/124056279

		$key = "vyhnYtwnHExqxbj6kGvjhpl6QQXS6Y13";
        $iv = "1234567890123456";
        // 加密
        function encrypt($input, $key, $iv){
            return base64_encode(openssl_encrypt($input, 'AES-256-CBC', $key, OPENSSL_RAW_DATA,$iv));
        }
        // 解密
        function decrypt($input, $key, $iv){
            return openssl_decrypt(base64_decode($input), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        }
        $str = '123456';
        echo "加密结果: ".encrypt($str, $key, $iv);
        $encrypt = '6H5HIbnvlq/7fnhNNNw6yg==';
        echo "解密结果: ".decrypt($encrypt, $key, $iv);

AES-128-ECB 加密解密

// 加密
function encrypt($data, $key){
     return base64_encode(openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA));
 }
 // 解密
 function decrypt($data, $key){
     return openssl_decrypt(base64_decode($data), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
 }
 $str = '123456';
 $key = "rgw650LaTlsnF3EE";
 echo "加密结果: ".encrypt($str, $key);
 $encrypt = 'Hk30cwHkDqyOuouYKtoxqg==';
 echo "解密结果: ".decrypt($encrypt, $key);
//最大4个字头像
function letter_avatar2($text)
{
    $total = unpack('L', hash('adler32', $text, true))[1];
    $hue = $total % 360;
    list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

    $bg = "rgb({$r},{$g},{$b})";
    $color = "#ffffff";
    $text=str_replace('有限','',$text);
    $text=str_replace('公司','',$text);
    $text=mb_strtoupper(mb_substr($text, 0, 4));

    $svg='<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect>';
    switch (mb_strlen($text)){
        case 1:
            $svg.='<text x="50" y="50" font-size="50"  fill="' . $color . '" text-anchor="middle"  dominant-baseline="central">' . $text . '</text>';
            break;
        case 2:
            $svg.='<text x="50" y="50" font-size="35"  fill="' . $color . '" text-anchor="middle"  dominant-baseline="central">' . $text . '</text>';
            break;
        case 3:
            $svg.='<text x="50" y="50" font-size="25"  fill="' . $color . '" text-anchor="middle"  dominant-baseline="central">' . $text . '</text>';
            break;
        case 4:
            $svg.='<text x="50" y="32" font-size="25"  fill="' . $color . '" text-anchor="middle"  dominant-baseline="central">' . mb_substr($text, 0, 2) . '</text>';
            $svg.='<text x="50" y="68" font-size="25"  fill="' . $color . '" text-anchor="middle"  dominant-baseline="central">' . mb_substr($text, 2, 2) . '</text>';
            break;
    }
    $svg.='</svg>';
    return 'data:image/svg+xml;base64,' . base64_encode($svg);
}

商品图片换域名

//商品图片换域名
        $goods=db('goods')->field('id,content')->select();$n=0;
        foreach ($goods as $good){
            $str=str_replace('https://xcx.juxinlegou.com','http://img.juxinlegou.com',$good['content']);
            if($str!=$good['content']){
                db('goods')->where('id',$good['id'])->update(['content'=>$str]);$n++;
            }
        }
        dump($n);die;

时间计算

/**
 * 时间计算
 * @param $time int 要计算的时间戳
 * @param $y    int 变更年数
 * @param $m    int 变更月数
 * @param $d    int 变更天数
 * @param $h    int 变更时数
 * @param $i    int 变更分数
 * @param $s    int 变更秒数
 * @param $w    int 变更周数
 * @return false|int 计算后的时间戳
 */
function compute($time,$y=0,$m=0,$d=0,$h=0,$i=0,$s=0,$w=0){
    list($year,$month,$day,$hour,$minute,$second)=explode('-',date("Y-m-d-H-i-s",$time));
    if($w!=0) $d+=$w*7;
    return mktime($hour+$h,$minute+$i,$second+$s,$month+$m,$day+$d,$year+$y);
}

/**
 * 时间加n个月,如果下一个月天数不够就自动返回下一月最后一天
 * @param $time int 时间戳
 * @param $key int 加几个月
 * @param $type int =0返回日期,=1返回时间戳
 * @return false|int|string
 */
function addDate($time, $key,$type=0)
{
    $day = date("d", $time);
    $date = date("Y-m-d", strtotime("$key month", $time));
    if ($day >28) {
        //获取下月,如果下月最后一天小于$day,返回下月最后一天
        $month = date("Y-m", strtotime("$key month",strtotime(date('Y-m',$time))));
        $max=date('t',strtotime($month));
        if ($max < $day) {
            $date = $month.'-'.$max;
        }
    }
    return $type==1 ? strtotime($date) : $date;
}

tp5 模型关联预载入+排序
模型写法

	public function video()
    {
        return $this->hasMany('Video', 'article_paid_id', 'id');
    }

控制器写法

 $id=input('id');
 $info=model('app\admin\model\article\Paid')->where('status','normal')->where('id',$id)
     ->with(['video'=>function($query){$query->order('weigh,id');}])->find();

关联预载入嵌套查询时,如果要限制返回字段那么关联的主键要显示出来。否则会报错

$order=model('app\admin\model\shopro\order\Order')->where('status','>',0)->where('createtime','BETWEEN',[$time1, $time2])
                ->with(['item'=>function($query){
                    $query->where('refund_status','<',1)->with(['goods'=>function($query){
                        $query->withField('id,anchor_id');
                    },'sku'=>function($query){
                        $query->withField('id,two_expert_ratio');
                    }]);
                }])->select();

根据数组元素的概率获得键名

/**
     * 根据数组元素的概率获得键名
     *
     * @param array $ps     array('p1'=>20, 'p2'=>30, 'p3'=>50);
     * @param int   $num    默认为1,即随机出来的数量
     * @param bool  $unique 默认为true,即当num>1时,随机出的数量是否唯一
     * @return mixed 当num为1时返回键名,反之返回一维数组
     */
    public static function lottery($ps, $num = 1, $unique = true)
    {
        if (!$ps) {
            return $num == 1 ? '' : [];
        }
        if ($num >= count($ps) && $unique) {
            $res = array_keys($ps);
            return $num == 1 ? $res[0] : $res;
        }
        $max_exp = 0;
        $res = [];
        foreach ($ps as $key => $value) {
            $value = substr($value, 0, stripos($value, ".") + 6);
            $exp = strlen(strchr($value, '.')) - 1;
            if ($exp > $max_exp) {
                $max_exp = $exp;
            }
        }
        $pow_exp = pow(10, $max_exp);
        if ($pow_exp > 1) {
            reset($ps);
            foreach ($ps as $key => $value) {
                $ps[$key] = $value * $pow_exp;
            }
        }
        $pro_sum = array_sum($ps);
        if ($pro_sum < 1) {
            return $num == 1 ? '' : [];
        }
        for ($i = 0; $i < $num; $i++) {
            $rand_num = mt_rand(1, $pro_sum);
            reset($ps);
            foreach ($ps as $key => $value) {
                if ($rand_num <= $value) {
                    break;
                } else {
                    $rand_num -= $value;
                }
            }
            if ($num == 1) {
                $res = $key;
                break;
            } else {
                $res[$i] = $key;
            }
            if ($unique) {
                $pro_sum -= $value;
                unset($ps[$key]);
            }
        }
        return $res;
    }

秒转文字

function human($second){
    $chunks = [
        [60 * 60 * 24 * 365, '年'],
        [60 * 60 * 24 * 30, '月'],
//        [60 * 60 * 24 * 7, '周'],
        [60 * 60 * 24, '天'],
        [60 * 60, '小时'],
        [60, '分钟'],
        [1, '秒']
    ];
    $name = '';
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
        $seconds = $chunks[$i][0];
        $count = floor($second / $seconds);
        if($count>=1){
            $name.=$count.$chunks[$i][1];
            $second-=$count*$seconds;
        }
    }
    return $name;
}

curl设置请求头Content-Type:application/x-www-form-urlencoded时,后端获取不到参数
原因是:请求体是数组,会被curl自动转成form-data格式。
解决办法:使用http_build_query($param)函数处理下请求体


/**
 * 判断坐标是否在多边形内
 * @param $aLon float 经度或者纬度
 * @param $aLat float 纬度或者经度
 * @param $pointList array 区域地点多边形点的顺序需根据顺时针或逆时针,不能乱
 * @return bool|int
 */
function is_ptin_poly($aLon, $aLat, $pointList = array())
{
    $iSum = 0;
    $iCount = count($pointList);
    if ($iCount < 3) {
        return false;
    }
    foreach ($pointList as $key => $row) {
        $pLon1 = $row[0];
        $pLat1 = $row[1];
        if ($key === $iCount - 1) {
            $pLon2 = $pointList[0][0];
            $pLat2 = $pointList[0][1];
        } else {
            $pLon2 = $pointList[$key + 1][0];
            $pLat2 = $pointList[$key + 1][1];
        }
        if ((($aLat >= $pLat1) && ($aLat < $pLat2)) || (($aLat >= $pLat2) && ($aLat < $pLat1))) {
            if (abs($pLat1 - $pLat2) > 0) {
                $pLon = $pLon1 - (($pLon1 - $pLon2) * ($pLat1 - $aLat)) / ($pLat1 - $pLat2);
                if ($pLon < $aLon) {
                    $iSum += 1;
                }
            }
        }
    }
    if ($iSum % 2 != 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 获取两个经纬度之间的距离
 * @param string $lat1 纬一
 * @param String $lng1 经一
 * @param String $lat2 纬二
 * @param String $lng2 经二
 * @return float  返回两点之间的距离,公里
 */
function calcDistance($lat1, $lng1, $lat2, $lng2)
{
    if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
        return false;
    }

    /** 转换数据类型为 double */
    $lat1 = doubleval($lat1);
    $lng1 = doubleval($lng1);
    $lat2 = doubleval($lat2);
    $lng2 = doubleval($lng2);

    $theta = $lng1 - $lng2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;

    return ($miles * 1.609344);
}

//金额大写

function get_amount($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    $num = bcmul(round($num, 2),100);
    if (strlen($num) > 11) {
        return "数据太长,没有这么大的钱吧,检查下";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = bcmod($num,10);
        }
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($p2 == '亿' || $p2 == '万' || $p2 == '元')) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        $num = bcdiv($num,10);
        $num = (int)$num;
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        $m = substr($c, $j, 6);
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        }
        $j = $j + 3;
    }

    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    if (empty($c)) {
        return "零元整";
    }else{
        return $c . "整";
    }
}

过滤特殊字符


//过滤特殊字符
function get_filter_str($str)
{
    preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u', $str, $result);
    return implode('', $result[0]);
}

//防止连点
function repeat_filter(){
    $key = md5(request()->baseUrl() . ':' . request()->ip());
    if (cache('?' . $key)) {
        return json([
            'code' => 0,
            'msg' => '请不要重复提交',
            'data' => null,
            'time' => time()
        ]);
    }
    cache($key, time(), 5);
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值