国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

laravel記錄

roland_reed / 1410人閱讀

摘要:開啟跨域對于跨域訪問并需要伴隨認證信息的請求,需要在實例中指定為在響應中指定為時,不能指定為自定義命令命令生成文件這里是命令行調用的名字如這里的命令行調用的時候就是這里填寫命令行的描述當執行

laravel開啟跨域
//對于跨域訪問并需要伴隨認證信息的請求,需要在 XMLHttpRequest 實例中指定 withCredentials 為 true,在響應中指定 Access-Control-Allow-Credentials 為 true 時,Access-Control-Allow-Origin 不能指定為 *
header("Access-Control-Allow-Origin", config("app.allow"));
        $response->header("Access-Control-Allow-Headers", "Origin, Content-Type, Cookie, Accept");
        $response->header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS");
        $response->header("Access-Control-Allow-Credentials", "true");
        return $response;
  }

}
laravel自定義artisan命令
//命令生成文件 app/Console/Commands/TopicMakeExcerptCommand.php
php artisan make:console TopicMakeExcerptCommand --command=topics:excerpt
excerpt))
          {
              $topic->excerpt = Topic::makeExcerpt($topic->body);
              $topic->save();
              $transfer_count++;
          }
        }
        $this->info("Transfer old data count: " . $transfer_count);
        $this->info("It"s Done, have a good day.");
    }
}
//在 app/Console/Kernel.php 文件里面, 添加以下
 protected $commands = [
        AppConsoleCommandsTopicMakeExcerptCommand::class,
    ];
//命令行調用
   php artisan topics:excerpt  
去除CSRF TOKEN的保護
Route::post("wechatmp", "WechatController@responseMsg");

class VerifyCsrfToken extends BaseVerifier
{

 protected $except = [
    "wechatmp", 
 ];
}
DateTime非常方便快捷地計算出兩個日期的diff
$datetime1 = new DateTime();
$datetime2 = new DateTime("2018-08-16");
$interval = $datetime1->diff($datetime2);
list($y, $m, $d) = explode("-", $interval->format("%Y-%m-%d"));

echo "距世界杯還有{$y}年{$m}個月{$d}天";
$now=time();
$end=strtotime("2018-8-16 00:00:00");
$d=$end-$now;

$y = date("Y", $d) - 1970;
$m = date("n", $d) - 1;
$d = date("j", $d) - 1;

printf("還有%d年%d月%d天", $y, $m, $d);
php里簡單的對稱加密算法
$content = "大家好,我是中國人,你是誰";

    /**
     * 簡單對稱加密算法之加密
     * @param String $string 需要加密的字串
     * @param String $skey 加密EKY
     * @return String
     */
    function encode($string = "", $skey = "wenzi") {
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key < $strCount && $strArr[$key].=$value;
        return str_replace(array("=", "+", "/"), array("O0O0O", "o000o", "oo00o"), join("", $strArr));
    }

    /**
     * 簡單對稱加密算法之解密
     * @param String $string 需要解密的字串
     * @param String $skey 解密KEY
     * @return String
     */
    function decode($string = "", $skey = "wenzi") {
        $strArr = str_split(str_replace(array("O0O0O", "o000o", "oo00o"), array("=", "+", "/"), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return base64_decode(join("", $strArr));
    }

    echo "
";
    echo "string : " . $content . " 
"; echo "encode : " . ($enstring = encode($content)) . "
"; echo "decode : " . decode($enstring);
laravel eloquent 一對一關聯后根據副表中的字段來排序
GoodsData::with("good")->whereHas("good", function($q) use ($brandId) {
    $q->where("brand_id", $brandId)
})->orderBy("click_count", "desc")->paginate();

$goodIds = GoodsData::whereHas("good", function($q) use ($brandId) {
    $q->where("brand_id", $brandId)
})->orderBy("click_count", "desc")->skip(10)->take(15)->pluck("id");

$goods = Good::whereIn("id", $goodIds)->get();
數字運算
function calc($m,$n,$x){
        $errors=array(
                "被除數不能為零",
                "負數沒有平方根"
        );
        switch($x){
                case "add":
                        $t=bcadd($m,$n);
                        break;
                case "sub":
                        $t=bcsub($m,$n);
                        break;
                case "mul":
                        $t=bcmul($m,$n);
                        break;
                case "div":
                        if($n!=0){
                                $t=bcdiv($m,$n);
                        }else{
                                return $errors[0];
                        }
                        break;
                case "pow":
                        $t=bcpow($m,$n);
                        break;
                case "mod":
                        if($n!=0){
                                $t=bcmod($m,$n);
                        }else{
                                return $errors[0];
                        }
                        break;
                case "sqrt":
                        if($m>=0){
                                $t=bcsqrt($m);
                        }else{
                                return $errors[1];
                        }
                        break;
        }
        $t=preg_replace("/..*0+$/","",$t);
        return $t;
}
/*用法舉例*/
echo calc("11111111111111111111111111111111110","10","add");
計算2點經緯度之間的距離代碼
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {  
    $theta = $longitude1 - $longitude2;  
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));  
    $miles = acos($miles);  
    $miles = rad2deg($miles);  
    $miles = $miles * 60 * 1.1515;  
    $feet = $miles * 5280;  
    $yards = $feet / 3;  
    $kilometers = $miles * 1.609344;  
    $meters = $kilometers * 1000;  
    return compact("miles","feet","yards","kilometers","meters");  
}  
  
$point1 = array("lat" => 40.770623, "long" => -73.964367);  
$point2 = array("lat" => 40.758224, "long" => -73.917404);  
$distance = getDistanceBetweenPointsNew($point1["lat"], $point1["long"], $point2["lat"], $point2["long"]);  
foreach ($distance as $unit => $value) {  
    echo $unit.": ".number_format($value,4)."
"; }
計算抽獎的概率
    function get_rand($proArr) {     
        $result = "";      
        $proSum = array_sum($proArr);       
        foreach ($proArr as $key => $proCur) {     
            $randNum = mt_rand(1, $proSum);     
            if ($randNum <= $proCur) {     
                $result = $key;     
                break;     
            } else {     
                $proSum -= $proCur;     
            }           
        }     
        unset ($proArr);      
        return $result;     
    }     
    $prize_arr = array(     
        "0" => array("id"=>1,"prize"=>"1000000514","v"=>2),     
        "1" => array("id"=>2,"prize"=>"1000000513","v"=>5),     
        "2" => array("id"=>3,"prize"=>"1000000512","v"=>13),     
        "3" => array("id"=>4,"prize"=>"1000000511","v"=>15),     
        "4" => array("id"=>5,"prize"=>"1000000510","v"=>25),     
        "5" => array("id"=>6,"prize"=>"1000000509","v"=>30),    
        "6" => array("id"=>7,"prize"=>"1000000508","v"=>10),   
    );     
    foreach ($prize_arr as $key => $val) {     
        $arr[$val["id"]] = $val["v"];     
    }     
    $rid = get_rand($arr);    
    $res["yes"] = $prize_arr[$rid-1]["prize"];   
    unset($prize_arr[$rid-1]);      
    shuffle($prize_arr);    
    $prize_arrcount = count($prize_arr);   
    for($i=0;$i<$prize_arrcount;$i++){     
        $pr[] = $prize_arr[$i]["prize"];     
    }     
    $res["no"] = $pr;     
    //抽獎結果  
    $ro = $res["yes"];  
    print_r($ro);  
一維數據轉多維
   $s =<<< TXT  
1 = 光電鼠標  
2 = 機械鼠標  
3 = 沒有鼠標  
1.1 = 黑色光電鼠標  
1.2 = 紅色光電鼠標  
1.2.1 = 藍牙紅色光電鼠標  
TXT;  
  
$res = array();  
foreach(preg_split("/[
]+/", $s) as $r) {  
 list($k, $txt) = explode(" = ", $r);  
 $p =& $res;  
 foreach(explode(".", $k) as $v) {  
   if(! isset($p[$v])) $p[$v] = array("txt" => $txt, "child" => array());  
   $p =& $p[$v]["child"];  
 }  
}  
  
print_r($res);  
打亂數組二維數組/多維數組
function shuffle_assoc($list) {   
if (!is_array($list)) return $list;   
  
$keys = array_keys($list);   
shuffle($keys);   
$random = array();   
foreach ($keys as $key)   
$random[$key] = shuffle_assoc($list[$key]);   
  
return $random;   
}   

function rec_assoc_shuffle($array)  
{  
  $ary_keys = array_keys($array);  
  $ary_values = array_values($array);  
  shuffle($ary_values);  
  foreach($ary_keys as $key => $value) {  
    if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {  
      $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);  
    }  
    $new[$value] = $ary_values[$key];  
  }  
  return $new;  
}  
curl 上傳文件
$curl = curl_init();
        
        if (class_exists("CURLFile")) {// 這里用特性檢測判斷php版本
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
               $data = array("file" => new CURLFile(realpath($source)));//>=5.5
        } else {
            if (defined("CURLOPT_SAFE_UPLOAD")) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array("file" => "@" . realpath($source));//<=5.5
        }
        
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1 );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
        $result = curl_exec($curl);
        $error = curl_error($curl);
數字遞歸組合并排列
function recursion($groups, $echo = "")
{
    $current = array_pop($groups);
    $end = empty($groups);

    $echo .= $echo ? "," : "";

    foreach (str_split($current) as $item) {
        $rEcho = $echo . $item;

        if ($end) {
            echo $rEcho . "
";
        } else {
            recursion($groups, $rEcho);
        }
    }
}

recursion(explode(",", "123,45,6789"));
php超出字符截取
 $text = "123456"; 
$charLength = 10; //字符串長度 
$content = mb_strlen($text, "UTF-8") <= $charLength ? $text : mb_substr($text, 0,$charLength,"UTF-8") . "...";
post json
        // form post json
        $ch        = curl_init();
        $timeout   = 300;
        $useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $json = "{"name":"value"}";
        $data["data"] = $json;       
        $data = http_build_query($data);
        curl_setopt($ch, CURLOPT_URL, "http://www.test.com/json.php");
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                        
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $body = curl_exec($ch);
        echo "
";print_r($body);
        //json.php
        var_dump($_POST);
        
        // 正確的post json
        $ch        = curl_init();
        $timeout   = 300;
        $useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
        $header    = array(
                "Accept-Language: zh-cn", 
                "Connection: Keep-Alive", 
                "Cache-Control: no-cache", 
                "Content-Type: Application/json;charset=utf-8"
            );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $json = "{"name":"value"}";
        curl_setopt($ch, CURLOPT_URL, "http://www.test.com/json.php");
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                        
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $body = curl_exec($ch);
        echo "
";print_r($body);
        //json.php
        var_dump(file_get_contents("php://input"));
        #curl命令行 post json
        #獲取本機ip地址
        $ curl http://httpbin.org/ip
        {"origin": "24.127.96.129"}
        $ curl -X POST -d "{"name":"value"}"  -H "Content-type: application/json" "http://httpbin.org/post"
        {
          "args": {},
          "data": "{"name":"value"}",
          "files": {},
          "form": {},
          "headers": {
            "Accept": "*/*",
            "Content-Length": "16",
            "Content-Type": "application/json",
            "Host": "httpbin.org",
            "User-Agent": "curl/7.30.0"
          },
          "json": {
            "name": "value"
          },
          "origin": "43.255.178.126",
          "url": "http://httpbin.org/post"
        }
        #python post json
        >>> import requests,json
        >>> headers = {"content-type": "application/json"}
        >>> payload = {"name": "value"}
        >>> r = requests.post("http://httpbin.org/post", data=json.dumps(payload), headers=headers)
        >>> print(r.json())
        
        
為 VerifyCsrfToken 添加過濾條件
//修改 app/Http/Middleware/VerifyCsrfToken.php 文件

自定義一個類文件讓composer加載
//修改composer.json文件:
{
    "require": {
        "illuminate/container": "^5.2"
    },
    "autoload": {
        "psr-4": {
            "App": "app/"
        }
    }
}
#composer install
// app/Test/Test.php文件
namespace AppTest;

class Test
{
    public function index()
    {
        echo "This is a custom class which will be autoload by composer
";
    }
}

//index.php
require_once __DIR__."/vendor/autoload.php";

$test = new AppTestTest();
$test->index();
利用 macro 方法來擴展 Laravel 的基礎類的功能
//創建一個ServiceProvider,并把擴充的方法,放入boot()的方法中
namespace AppProviders;

  use Collection;
  use IlluminateSupportServiceProvider;

  class CollectionMacroServiceProvider extends ServiceProvider {

      public function boot()
      {
         Collection::macro("uppercase", function () {
         //$this不是指向你文件類的對象,而是指向你marco擴充的類。比如例子中的$this是指向Collection的。
            return collect($this->items)->map(function ($item) {
                return strtoupper($item);
            });
        });
      }

  }
//在config/app.php中的providers中下面添加AppProvidersCollectionMacroServiceProvider::class即可
從現有數據庫表中生成 Model 模型文件
composer require ignasbernotas/laravel-model-generator
在 app/Providers/AppServiceProvider.php 文件的 register 方法里面,加入如下代碼

public function register()
{
    if ($this->app->environment() == "local") {
        $this->app->register("IberGeneratorModelGeneratorProvider");
    }
}
php artisan make:models
數組扁平化
$arrays = array(0 => Array (
                    0 => Array (
                        "社員" => 2,
                         0 => "level4"
                    ),
                    1 => Array (
                        "社員" => 2,
                         0 => "level4",
                         1 => "level4"
                    )
               ),
               1 => Array (
                    0 => Array (
                        "小組長" => 2,
                        0 => "level3"
                    ),
                    1 => Array (
                        "小組長" => 2,
                        0 => "level3",
                        1 => "level2",
                        2 => "level3"
                    )
               )
    );
    dd(collect($arrays)->map(function($array){
        return $array[1]; //比如都取最里面數組的第二個值
    })->flatten(1));
Laravel 單點登錄
php artisan make:middleware SsoMiddleware
將中間件添加到 Kernel.php
protected $routeMiddleware = [
        "auth" => AppHttpMiddlewareAuthenticate::class,
        "auth.basic" => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        "guest" => AppHttpMiddlewareRedirectIfAuthenticated::class,
        "SsoMiddleware" => AppHttpMiddlewareindexSsoMiddleware::class,
    ];

/**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest $request
     * @param  Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userInfo = Session::get("user_login");
        if ($userInfo) {
            // 獲取 Cookie 中的 token
            $singletoken = $request->cookie("SINGLETOKEN");
            if ($singletoken) {
                // 從 Redis 獲取 time
                $redisTime = Redis::get(STRING_SINGLETOKEN_ . $userInfo->guid);
                // 重新獲取加密參數加密
                $ip = $request->getClientIp();
                $secret = md5($ip . $userInfo->guid . $redisTime);
                if ($singletoken != $secret) {              
                    // 記錄此次異常登錄記錄
                    DB::table("data_login_exception")->insert(["guid" => $userInfo->guid, "ip" => $ip, "addtime" => time()]);
                    // 清除 session 數據
                    Session::forget("indexlogin");
                    return view("/403")->with(["Msg" => "您的帳號在另一個地點登錄.."]);
                }
                return $next($request);
            } else {
                return redirect("/login");
            }
        } else {
            return redirect("/login");
        }
    }
    // 有 Sso 中間件的路由組
Route::group(["middleware" => "SsoMiddleware"], function() {
      # 用戶登錄成功后的路由
}
curl ssl
$url="https://api.shanbay.com/bdc/search/?word=hello";
$ch=curl_init();
$timeout=5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data=curl_exec($ch);
curl_close($ch);
echo $data;
base64_encode進行編碼.同時替換其中的不安全字符
//處理為URL安全模式
function reflowURLSafeBase64($str){
    $str=str_replace("/","_",$str);
    $str=str_replace("+","-",$str);
    return $str;
}

//反解
function reflowNormalBase64($str){
    $str=str_replace("_","/",$str);
    $str=str_replace("-","+",$str);
    return $str;
}
PHP無限級分類
function data_to_tree(&$items, $topid = 0, $with_id = TRUE)
{
    $result = [];
    foreach($items as $v)
        if ($topid == $v["parent"])  {
            $r = $v + ["children" => _data_to_tree($items, $v["id"], $with_id)];
            if ($with_id)
                $result[$v["id"]] = $r;
            else
                $result[] = $r;
        }
            
    return $result;
}
function _data_to_tree($items, $topid = 0, $with_id = TRUE)
{
    if ($with_id)
        foreach ($items as $item)
            $items[ $item["parent"] ]["children"][ $item["id"] ] = &$items[ $item["id"] ];
    else
        foreach ($items as $item)
                $items[ $item["parent"] ]["children"][] = &$items[ $item["id"] ];

         return isset($items[ $topid ]["children"]) ? $items[ $topid ][ "children" ] : [];
}
$data = [
   ["id" => 4, "parent" => 1 , "text" => "Parent1"], 
   ["id" => 1, "parent" => 0 , "text" => "Root"],
   ["id" => 2, "parent" => 1 , "text" => "Parent2"], 
   ["id" => 3, "parent" => 2 , "text" => "Sub1"], 
];
print_r ( _data_to_tree($data, 0) );

Array
(
    [1] => Array
        (
            [id] => 1
            [parent] => 0
            [text] => Root
            [children] => Array
                (
                    [4] => Array
                        (
                            [id] => 4
                            [parent] => 1
                            [text] => Parent1
                            [children] => Array
                                (
                                )
                        )
                    [2] => Array
                        (
                            [id] => 2
                            [parent] => 1
                            [text] => Parent2
                            [children] => Array
                                (
                                    [3] => Array
                                        (
                                            [id] => 3
                                            [parent] => 2
                                            [text] => Sub1
                                            [children] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )
)
判斷是否為json格式
function is_json($string) 
{
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
//return json_encode($json)!==false
}

$str = "{"id":23,"name":"test"}";
var_dump(is_json($str));
中文英文截取
/**
 * 移除字符串的BOM
 *
 * @param  string $str 輸入字符串
 * @return string 輸出字符串
 */
function removeBOM($str)
{
    $str_3 = substr($str, 0, 3);
    if ($str_3 == pack("CCC",0xef,0xbb,0xbf)) //utf-8
        return substr($str, 3);
    return $str;
}

/**
 * 按UTF-8分隔為數組,效率比MB_Substr高
 * 0xxxxxxx
 * 110xxxxx 10xxxxxx
 * 1110xxxx 10xxxxxx 10xxxxxx
 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
 *
 * @param string $str 輸入utf-8字符串
 * @return array 返回成一段數組
 */
function str_split_utf8($str)
{
    return preg_match_all("/./u", removeBOM($str), $out) ? $out[0] : FALSE;
}

/**
 * 按非ascii字符占有幾個字寬的方式切分字符串,并且不會將漢字切成半個
 * 所謂字寬是指,使用默認字體顯示時,非ascii字符相比英文字符所占大小,比如:宋體、微軟雅黑中,漢字占兩個寬度
 * @example $ansi_width = 2 表示漢字等非英文字符按照兩個字寬長度
 * @example $ansi_width = 1 表示所有字符按一個字寬長度
 *
 * @param string $string 原始字符
 * @param integer $offset 開始偏移,使用方法和substr一樣,可以為負數
 * @param integer $length 長度,使用方法和substr一樣,可以為負數
 * @param integer $ansi_width 漢字等非英文字符按照幾個字符來處理
 * @return string 返回裁減的字符串
 */
function substr_ansi($string, $offset, $length = 0, $ansi_width = 1)
{
    if (empty($string)) return $string;;
    $data = str_split_utf8($string);
    if (empty($data)) return $string;
 
    $as = $_as = array();
    $_start = $_end = 0;
 
    foreach($data as $k => $v)
        $as[$k] = strlen($v) > 1 ? $ansi_width : 1;
 
    $_as_rev = array_reverse($as,true);
    $_as = $offset < 0 ? $_as_rev : $as; 
    $n = 0; $_offset = abs($offset);
    foreach($_as as $k => $v) {
        if ($n >= $_offset) {
            $_start = $k;
            break;
        }
        $n += $v;
    }
    //echo $_start,",";
    $_as = $length <= 0 ? $_as_rev : $as;
    end($_as); list($_end) = each($_as); reset($_as);//給$_end 設定默認值,一直到結尾
    $n = 0; $_length = abs($length);
    foreach($_as as $k => $v) {
        if ($k >= $_start) {
            if ($n >= $_length) {
                $_end = $k + ($length <= 0 ? 1 : 0);
                break;
            }
            $n += $v;
        }
    }
    //echo $_end,"|||||";
    if ($_end <= $_start)
        return "";
 
    $_data = array_slice($data, $_start, $_end - $_start);
 
    return implode("",$_data);
}

/**
 * 按非ascii字符占有幾個字寬的方式計算字符串長度
 * @example $ansi_width = 2 表示漢字等非英文字符按照兩個字寬長度
 * @example $ansi_width = 1 表示所有字符按一個字節長度
 *
 * @param string $string 原始字符
 * @param integer $ansi_width 漢字等非英文字符按照幾個字寬來處理
 * @return string 返回字符串長度
 */
function strlen_ansi($string, $ansi_width = 1)
{
    if (empty($string)) return 0;
    $data = str_split_utf8($string);
    if (empty($data)) return 0;
 
    $as = 0;
    foreach($data as $k => $v)
        $as += strlen($v) > 1 ? $ansi_width : 1;
    unset($data);
    return $as;
}

/**
 * smarty truncate 代碼算法來自于Smarty
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @param boolean
 * @return string
 */
function truncate($string, $length = 80, $etc = "...", $break_words = false, $middle = false)
{
    if ($length == 0)
        return "";
    $ansi_as = 2;
    if (strlen_ansi($string, $ansi_as) > $length) {
        $length -= min($length, strlen_ansi($etc, $ansi_as));
        if (!$break_words && !$middle) {
            $string = preg_replace("/s+?(S+)?$/u", "", substr_ansi($string, 0, $length+1, $ansi_as));
        }
        if(!$middle) {
           return substr_ansi($string, 0, $length, $ansi_as) . $etc;
        } else {
            return substr_ansi($string, 0, $length/2, $ansi_as) . $etc . substr_ansi($string, -$length/2, 0,  $ansi_as);
        }
    } else {
        return $string;
    }
}
// substr_ansi ($offset, $length, $ansi_width)
// 如果ansi_width = 2,則表示將漢字當做2個寬度處理
// offset length 在實際截取過程中,以英文的長度為準即可

echo substr_ansi("漢字我愛你", 0, 5, 2);     //輸出:漢字我
echo substr_ansi("漢字abc我愛你", 0, 5, 2);  //輸出:漢字a
echo substr_ansi("abcdef", 0, 5, 2);        //輸出:abcde

echo mb_substr("漢字我愛你", 0, 5);          //輸出:漢字我愛你
echo mb_substr("漢字abc我愛你", 0, 5);       //輸出:漢字abc
echo mb_substr("abcdef", 0, 5);             //輸出:abcde
命令行獲取ip地址
 curl http://ip.3322.net/ 
curl -4 -s icanhazip.com  
curl myip.ipip.net 
curl ip.cn 
curl httpbin.org/ip 
curl https://www.v2ex.com/ip | grep "ip="  
curl ifconfig.io 
curl ifconfig.me 
curl http://ip.taobao.com/service/getIpInfo2.php?ip=myip
顏值計算類
 

/**
* 排名算法
*/
class Rank
{
    private static $K = 32;
    private static $db;        //數據庫連接對象
    function __construct()
    {
        require_once "DBMysql.php";
        self::$db = DBMysql::connect();
    }

  //根據id值查詢顏值
    public function queryScore($id)
    {
        $sql = "SELECT * FROM stu WHERE `id` = $id";
        $info = mysqli_fetch_assoc(self::$db->query($sql));
        return $info["score"];
    }
    //更新顏值
    public function updateScore($Ra,$id)
    {
        self::$db->query("UPDATE `stu` SET `score` = $Ra WHERE `id` = $id");
    }

  //計算二者的勝率期望值
    public function expect($Ra,$Rb)
    {
        $Ea = 1/(1+pow(10,($Rb-$Rb)/400));
        return $Ea;
    }

    //計算最后得分
    public function calculateScore($Ra,$Ea,$num)
    {
        $Ra = $Ra + self::$K*($num-$Ea);
        return $Ra;
    }

  //獲取本次參與評選的兩位美女id,以及獲勝方id:0,1
    public function selectStu()
    {
        $id1 = $_POST["stu1"];
        $id2 = $_POST["stu2"];
        $victoryid = $_POST["vid"];
        return $this->getScore($id1,$id2,$victoryid);
    }

  //計算得分
    public function getScore($id1,$id2,$victoryid)
    {
        $Ra = $this->queryScore($id1);
        $Rb = $this->queryScore($id2);
        if ($Ra & $Rb) {
            $Ea = $this->expect($Ra, $Rb);
            $Eb = $this->expect($Rb, $Ra);
            $Ra = $this->calculateScore($Ra, $Ea, 1-$victoryid);
            $Rb = $this->calculateScore($Rb, $Eb, $victoryid);
            $Rab = array($Ra,$Rb);
            $this->updateScore($Ra, $id1);
            $this->updateScore($Rb, $id2);
            return $Rab;
        } else {
            return false;
        }
    }
}
$Rank = new Rank();
$Rank->selectStu();
第二個數組按第一個數組的鍵值排序
$a = [
    "id",
    "name",
    "identityId",
    "phone",
    "email",
    "schoolId"
];

$b = [
    "id" => "唯一標識",
    "identityId" => "身份證",
    "phone" => "手機號",
    "email" => "郵箱",
    "name" => "姓名",
    "schoolId" => "學校"
];

var_dump(array_merge(array_flip($a), $b));
$arr1 = array(
    "id",
    "name",
    "identityId",
    "phone",
    "email",
    "schoolId"
);
$arr2 = array(
    "id" => "唯一標識",
    "identityId" => "身份證",
    "phone" => "手機號",
    "email" => "郵箱",
    "name" => "姓名",
    "schoolId" => "學校",
);
array_multisort($arr1,SORT_DESC,$arr2);
print_r($arr2);
// 結果為:
Array
(
    [schoolId] => 學校
    [email] => 郵箱
    [identityId] => 身份證
    [phone] => 手機號
    [id] => 唯一標識
    [name] => 姓名
)
$c = array();
foreach ($a as $value) $c[$value] = $b[$value];
print_r($c);
正則
[] 的意思匹配指定字符,而不是字符串
(string1|string2) 才是匹配多個字符串
(?! string1) 匹配 非 字符串

$text = "
"; $pattern="/<.*?[input|textarea|select].*?>/i";///<.*?(input|textarea|select).*?>/is preg_match($pattern1,$text,$matches); var_dump($matches); //正則 $p = "#.*?)>(?.*?)(?kolja;a"; echo "encode : " . ($enstring = encode($content)) . "
"; echo "decode : " . decode($enstring);
使用 MPDF 將HTML轉為PDF
$html = "對盲人初學者來說,它無需任何額外的修改。";
// $html = "These are the most used acronyms throughout this manual.";
include "./mpdf/mpdf.php";
$mpdf=new mPDF("utf-8");   //這里改成UTF-8 即可 
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML($html);
$mpdf->Output();
strtr vs str_replace
$arr = array("中國", "中國人"); //關鍵字
foreach($arr as $v) { $new[$v] = "".$v.""; }
var_export($new); //輸出: array( "中國" => "中國", "中國人" => "中國人" )
$str = "我是中國人我愛中國";
echo strtr($str, $new)."
"; //輸出: 我是中國人我愛中國

//對比:str_replace會發生重復替換,下面代碼會輸出: 我是中國我愛中國
echo str_replace(array("中國人","中國"), array("中國人","中國"), "我是中國人我愛中國");
判斷文件類型
$image=file_get_contents($url);
file_put_contents($imagePath, $image);   //將圖片流存入服務器圖片目錄
$type=image_type_to_extension(exif_imagetype($imagePath));   //文件類型

$image = file_get_contents($url);

echo check_image_type($image);

function check_image_type($image)
{
    $bits = array(
        "JPEG" => "xFFxD8xFF",
        "GIF" => "GIF",
        "PNG" => "x89x50x4ex47x0dx0ax1ax0a",
        "BMP" => "BM",
    );
    foreach ($bits as $type => $bit) {
        if (substr($image, 0, strlen($bit)) === $bit) {
            return $type;
        }
    }
    return "UNKNOWN IMAGE TYPE";
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
var_dump($finfo->file("t.jpg")); // ==> image/jpeg
php Unicode正則
$str=json_decode(""ux這u202eわかぃまぃだDD"");
    var_dump($str);//string(28) "ux這?わかぃまぃだDD"

    var_dump(preg_match("/^[wx{4e00}-x{9aff}]{4,12}$/u", $str,$match));//int(0)
    var_dump($match);
數組order by
$arr = array(
 "中國" => array(
     "金牌" => 8,
     "銀牌" => 3,
     "銅牌" => 6,
 ),
 "俄羅斯" => array(
     "金牌" => 3,
     "銀牌" => 6,
     "銅牌" => 3,
 ),
 "美國" => array(
     "金牌" => 6,
     "銀牌" => 8,
     "銅牌" => 8,
 ),
 "澳大利亞" => array(
     "金牌" => 4,
     "銀牌" => 0,
     "銅牌" => 4,
 ),
 "意大利" => array(
     "金牌" => 3,
     "銀牌" => 4,
     "銅牌" => 2,
 ),

);
// 實現 ORDER BY
foreach($arr as $k => $v) {
 $sort["金牌"][$k] = $v["金牌"];
 $sort["銀牌"][$k] = $v["銀牌"];
 $sort["銅牌"][$k] = $v["銅牌"];
}
array_multisort(
 $sort["金牌"], SORT_DESC, 
 $sort["銀牌"], SORT_DESC, 
 $sort["銅牌"], SORT_DESC, 
 $arr);
var_export($arr);
arr = [
 {"name":"國家一","score":[10,7,5]},
 {"name":"國家二","score":[10,9,5]},
 {"name":"國家三","score":[11,7,5]},
 {"name":"國家四","score":[10,7,9]},
]

print sorted(arr, key=lambda a: "%03d%03d%03d" % tuple(a["score"]), reverse=True)
base64圖片處理
/**
 * 保存64位編碼圖片
 */

 function saveBase64Image($base64_image_content){

        if (preg_match("/^(data:s*image/(w+);base64,)/", $base64_image_content, $result)){

                  //圖片后綴
                  $type = $result[2];

                  //保存位置--圖片名
                  $image_name=date("His").str_pad(mt_rand(1, 99999), 5, "0", STR_PAD_LEFT).".".$type;
                  $image_url = "/uploads/image/".date("Ymd")."/".$image_name;           
                  if(!is_dir(dirname(".".$image_url))){
                         mkdir(dirname(".".$image_url));
                        chmod(dirname(".".$image_url), 0777);
                        umask($oldumask);

                  }
                 
                  //解碼
                  $decode=base64_decode(str_replace($result[1], "", $base64_image_content));
                  if (file_put_contents(".".$image_url, $decode)){
                        $data["code"]=0;
                        $data["imageName"]=$image_name;
                        $data["url"]=$image_url;
                        $data["msg"]="保存成功!";
                  }else{
                    $data["code"]=1;
                    $data["imgageName"]="";
                    $data["url"]="";
                    $data["msg"]="圖片保存失敗!";
                  }
        }else{
            $data["code"]=1;
            $data["imgageName"]="";
            $data["url"]="";
            $data["msg"]="base64圖片格式有誤!";


        }       
        return $data;


 }
php strtotime 獲取上周一的時間
>>> date("Y-m-d H:i:s",strtotime("-2 monday"))
=> "2016-10-03 00:00:00"
$days = date("w")==0?13:date("w")+6;

echo date("Y-m-d",time()-$days*86400);
date("Y-m-d", strtotime("-" . (6+date("w")) . " days"));
合并數組
$arr = array(
  "0" => array(
    "id" => 1,
    "count" =>1,
    ),
  "1" => array(
    "id" => 2,
    "count" =>1,
    ),
  "2" => array(
    "id" => 4,
    "count" =>1,
    ),
  "3" => array(
    "id" => 2,
    "count" =>1,
    ),
  );
$new = $news = $newss = array();
foreach ($arr as $key => $value) {
  
  if(!in_array($value["id"], $new)) {
    $new[] = $value["id"];  //$new保存不重復的id值
    $news[$key] = $value;   //$news保存不重復id的數組值
    $newss[$value["id"]] = $key;  //$newss保存不重復的id的鍵值
  }else {
    $k = $newss[$value["id"]];  //取出重復的id保存的第一個鍵值
    $count = (int)$news[$k]["count"];  //取出第一個相同id保存的count值
    $news[$k]["count"] = $count+1;     //賦值到新的數組
  }
}

var_dump($news);

https://github.com/iScript/YCms
https://phphub.org/topics/1759
http://blog.csdn.net/phpfengh...
https://phphub.org/topics/252...
http://www.xiabingbao.com/enc...

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/21905.html

相關文章

  • 記一次 Laravel 應用性能調優經歷

    摘要:為了一探究竟,于是開啟了這次應用性能調優之旅。使用即時編譯器和都能輕輕松松的讓你的應用程序在不用做任何修改的情況下,直接提高或者更高的性能。 這是一份事后的總結。在經歷了調優過程踩的很多坑之后,我們最終完善并實施了初步的性能測試方案,通過真實的測試數據歸納出了 Laravel 開發過程中的一些實踐技巧。 0x00 源起 最近有同事反饋 Laravel 寫的應用程序響應有點慢、20幾個并...

    warkiz 評論0 收藏0
  • 10 個優質的 Laravel 擴展推薦

    摘要:優點使用簡單服務自定義數據庫查詢生成多重定制哪里獲取表單構造器說實話,我不喜歡在中混合表單。表單構造器能夠讓你的表單從視圖中分離出去。功能多數據庫多域名和子域名自動生成或者配置文件支持隊列支持文件分開存儲。 showImg(https://segmentfault.com/img/remote/1460000015090896); 這里有 10+ 個用來搭建 Laravel 應用的包 ...

    simon_chen 評論0 收藏0
  • 無頭瀏覽器測試可視化:Laravel Dusk 控制臺入門指南

    摘要:通過添加此功能,該程序包將啟用記錄請求和響應信息所需的功能。是一條普通控制器路由,用于輸出控制臺的視圖。收集瀏覽器行為這是整個擴展包最乏味的部分。 Laravel Dusk 控制臺是一款 Laravel 擴展包,能夠為你的 Dusk 測試套件提供漂亮的可視面板。通過它,你可以可視化運行 Dusk 測試時涉及的各個步驟,以及查看每個步驟的 DOM 快照。這對于調試瀏覽器測試、并搞清楚后臺...

    levius 評論0 收藏0
  • laravel開發擴展記錄

    摘要:自動代碼擴展開發時遵守的代碼風格是項目開發規范。遵照此規范,在實際操作中,有許多重復,接下來推薦一款專為此規范量身定制的代碼生成器。可以利用此擴展來快速構建項目原型。后續還會為大家帶來一些最新的技術擴展。 whoops 錯誤提示擴展 whoops 是一個非常優秀的 PHP Debug 擴展,它能夠使你在開發中快速定位出錯的位置。laravel默認安裝。showImg(https://s...

    fancyLuo 評論0 收藏0
  • laravel開發擴展記錄

    摘要:自動代碼擴展開發時遵守的代碼風格是項目開發規范。遵照此規范,在實際操作中,有許多重復,接下來推薦一款專為此規范量身定制的代碼生成器。可以利用此擴展來快速構建項目原型。后續還會為大家帶來一些最新的技術擴展。 whoops 錯誤提示擴展 whoops 是一個非常優秀的 PHP Debug 擴展,它能夠使你在開發中快速定位出錯的位置。laravel默認安裝。showImg(https://s...

    魏憲會 評論0 收藏0

發表評論

0條評論

roland_reed

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<