分类 PHP 下的文章

Carbon 时间类常用方法

需要本地化,修改app/Providers/AppServiceProvider.php文件

public function boot()
{
    //Carbon 本地化
    \Carbon\Carbon::setLocale('zh');
    //添加mysql最大字符串限制
    Schema::defaultStringLength(191);
}

常用方法

$dt = Carbon::create(1975, 12, 25, 14, 15, 16);

var_dump($dt->toDateTimeString() == $dt);          // bool(true) => uses __toString()
echo $dt->toDateString();                          // 1975-12-25
echo $dt->toFormattedDateString();                 // Dec 25, 1975
echo $dt->toTimeString();                          // 14:15:16
echo $dt->toDateTimeString();                      // 1975-12-25 14:15:16
echo $dt->toDayDateTimeString();                   // Thu, Dec 25, 1975 2:15 PM

$dt = Carbon::now();

// $dt->toAtomString() is the same as $dt->format(DateTime::ATOM);
echo $dt->toAtomString();      // 1975-12-25T14:15:16-05:00
echo $dt->toCookieString();    // Thursday, 25-Dec-1975 14:15:16 EST
echo $dt->toIso8601String();   // 1975-12-25T14:15:16-0500
echo $dt->toRfc822String();    // Thu, 25 Dec 75 14:15:16 -0500
echo $dt->toRfc850String();    // Thursday, 25-Dec-75 14:15:16 EST
echo $dt->toRfc1036String();   // Thu, 25 Dec 75 14:15:16 -0500
echo $dt->toRfc1123String();   // Thu, 25 Dec 1975 14:15:16 -0500
echo $dt->toRfc2822String();   // Thu, 25 Dec 1975 14:15:16 -0500
echo $dt->toRfc3339String();   // 1975-12-25T14:15:16-05:00
echo $dt->toRssString();       // Thu, 25 Dec 1975 14:15:16 -0500
echo $dt->toW3cString();       // 1975-12-25T14:15:16-05:00

echo Carbon::now()->tzName;                        // America/Toronto
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');

echo $first->toDateTimeString();                   // 2012-09-05 23:26:11
echo $first->tzName;                               // America/Toronto
echo $second->toDateTimeString();                  // 2012-09-05 20:26:11
echo $second->tzName;                              // America/Vancouver

# 可以使用 parse 方法解析任何顺序和类型的日期(结果为 Carbon 类型的日期时间对象):

echo Carbon::parse('2016-10-15')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('2016-10-15')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('2016-10-15 00:10:25')->toDateTimeString(); //2016-10-15 00:10:25

echo Carbon::parse('today')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('yesterday')->toDateTimeString(); //2016-10-14 00:00:00
echo Carbon::parse('tomorrow')->toDateTimeString(); //2016-10-16 00:00:00
echo Carbon::parse('2 days ago')->toDateTimeString(); //2016-10-13 20:49:53
echo Carbon::parse('+3 days')->toDateTimeString(); //2016-10-18 20:49:53
echo Carbon::parse('+2 weeks')->toDateTimeString(); //2016-10-29 20:49:53
echo Carbon::parse('+4 months')->toDateTimeString(); //2017-02-15 20:49:53
echo Carbon::parse('-1 year')->toDateTimeString(); //2015-10-15 20:49:53
echo Carbon::parse('next wednesday')->toDateTimeString(); //2016-10-19 00:00:00
echo Carbon::parse('last friday')->toDateTimeString(); //2016-10-14 00:00:00

// The most typical usage is for comments
// The instance is the date the comment was created and its being compared to default now()
echo Carbon::now()->subDays(5)->diffForHumans();               // 5 days ago

echo Carbon::now()->diffForHumans(Carbon::now()->subYear());   // 1 year after

$dt = Carbon::createFromDate(2011, 8, 1);

echo $dt->diffForHumans($dt->copy()->addMonth());              // 1 month before
echo $dt->diffForHumans($dt->copy()->subMonth());              // 1 month after

echo Carbon::now()->addSeconds(5)->diffForHumans();            // 5 seconds from now

echo Carbon::now()->subDays(24)->diffForHumans();              // 3 weeks ago
echo Carbon::now()->subDays(24)->diffForHumans(null, true);    // 3 weeks

echo Carbon::create(2018, 2, 26, 4, 29, 43)->diffForHumans(Carbon::create(2016, 6, 21, 0, 0, 0), false, false, 6); // 1 year 8 months 5 days 4 hours 29 minutes 43 seconds after

You can also change the locale of the string using Carbon::setLocale('fr') before the diffForHumans() call. See the localization section for more detail.

冒泡排序

将数组中的相邻元素的比较和交换来把小的数交换到最前面

//冒泡排序
function maopao($num)
{
    for ($i = 0; $i < count($num); $i++) {
        for ($j = 0; $j < count($num) - $i - 1; $j++) {
            if ($num[$j] > $num[$j + 1]) {
                list($num[$j],$num[$j+1]) = [$num[$j+1],$num[$j]];
                //$tmp = $num[$j + 1];
                //$num[$j + 1] = $num[$j];
                //$num[$j] = $tmp;
            }
        }
    }
    return $num;
}

- 阅读剩余部分 -

  1. 在七牛控制台中创建Bucket。
  2. 下载PHP-SDK包。

可以通过composer来安装 composer require qiniu/php-sdk

  1. 获取密钥信息: AccessKey、SecretKey。
  2. 项目中将文件直接传至七牛服务器、通过回调来返回需要的数据、减轻业务服务器压力。

具体逻辑:

-  客户端获取服务器颁发的上传凭证(token)。
-  客户端上传资源至七牛,并带上token作为请求内容的一部分。
-  七牛处理资源、带上参数访问回调地址。
-  回调接口处理数据返回七牛。
-  七牛返回回调接口的处理数据给客户端。

demo:

//laravel中获取上传token
public function qiniu_token ()
    {
        //用户ID加密处理.
        $uid    = $this->hashid_enconde(Auth::user()->id);
        $bucket = env('QINIU_BUCKET');
        $policy = [
            'x:uid'            => $uid,
            //回调域名
            //Laravel中回调地址尽量走api路由、走web路由post过来的数据会因为csrf验证而导致419错误
            'callbackUrl'      => env('QINIU_CALLBACK'),
            //回调中需要传给服务器的数据、其中有七牛的魔法参数、和自定义的参数
            'callbackBody'     => '{"fname":"$(fname)", "fkey":"$(key)", "mimeType":"$(mimeType)","fsize":"$(fsize)", "uid":"'.
                                  $uid.'"}',
            'callbackBodyType' => 'application/json',
            //自定义文件存储路径(七牛中就是一串字符串...)
            'saveKey'          => "tools/".$uid."/$(year)/$(mon)/$(etag)$(ext)",
        ];
        $auth = new \Qiniu\Auth();
        
        return $auth->uploadToken($bucket, null, 3600, $policy);
    }

回调策略详见 文档

Blade 模板

@extends('layouts.app')
@section('content')
    <div class="container">
        <bill :upload-token="{{$token}}"></bill>
    </div>
@endsection

前端upload组件(iviewui)bill.vue

<template>
    <div>
         <Upload
                  ref="upload"
                  multiple
                  :data="uploadToken"
                  :default-file-list="uploadList"
                  :on-success="handleUploadSuccess"
                  :format="['jpg','jpeg','png']"
                  <!-- 此处填写七牛服务器地址 -->
                  action="https://upload.qiniup.com">
            <Button icon="ios-cloud-upload-outline">图片上传</Button>
          </Upload>
        <input v-model="images_url"></input>
    </div>
</template>

<script>
    export default{
        props:{
            uploadToken: Object
        },
        data(){
            return{
                uploadList:[],
                images_url:[],
            }
        },
        methods:{
            handleUploadSuccess(){
                this.$Message.success('图片上传成功');
                this.images_url.push(res.data);
            }
        }
    }
</script>

回调:

    /**
     * 持久化媒体文件
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function qiniuCallback (Request $request)
    {
        //将文件信息存入数据库中
        $media = Media::create([
            'user_id'     => $this->hashid_decode($request->get('uid')),
            'name'        => $request->get('fname'),
            'key'         => $request->get('fkey'),
            'mimeType'    => $request->get('mimeType'),
            'size'        => $request->get('fsize'),
            'description' => $request->get('des'),
        ]);
        //$media->url 使用Eloquent模型访问器功能生成图片路径,回调返回参数可自定义
        return $this->successResponseData(200, $media->url);
    }
  1. 上传资源完成之后可以通过异步数据处理将图片裁剪、添加水印。也是在上传策略中配置。详见

Laravel 框架中对 Mysql 查询复查语句的时候,有时候会遇到sql在MySQL终端中运行没问题,但是在laravel中出现错误.

  • 举个

查询表中name有重复的数据

$sql = " `name` IN (SELECT `name` FROM clients child GROUP BY child.`name` HAVING COUNT(child.`name`) > 1 ) ORDER BY `name`";

$clients = Client::whereRaw($sql)->paginate();

通过toSql()将sql打出来放到mysql终端中执行是没有问题的,但是在laravel框架中则会出现:

Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

  • 解决办法

config/database.php中mysql的 strict改为false就可以啦!