lovecn / lovecn.github.io

个人记录
5 stars 5 forks source link

php tips #45

Open lovecn opened 7 years ago

lovecn commented 7 years ago
filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range" => $max))); 
filter_var($int, FILTER_VALIDATE_INT,array('options' => array('min_range' => $min)));
$arr=array();

while(count($arr)<10)

{

    $arr[]=rand(1,10);

    $arr=array_unique($arr);

} sprintf("%.2f", $num);  同round
 $num = 123213.666666;  
echo sprintf("%.2f",substr(sprintf("%.3f", $num), 0, -2));  
$a= 123213.666666;
$i = 2; //保留几位
$len = pow(10,$i);
echo floor($a*$len)/$len;floor($num * 100) / 100

PHP大整数输出成科学计数法问题
$str =2228282829299292;
 //失败
echo (string)$str;  //2.2282828292993E+15  失败
echo '<br>';
echo ' '.$str; //2.2282828292993E+15
echo '<br>';
echo strval($str); //2.2282828292993E+15
echo '<br>';
 //成功
echo sprintf("%.0f", $str);
echo '<br>';
echo number_format($str);// 三位逗号分隔
高亮中文$string="I Love 黑帽联盟www.heimaolianmeng.com";
echo preg_replace("/([\x80-\xff]+)/","<font color=red>\\1</font>",$string);

if(PATH_SEPARATOR == ':'){
return 'Linux';
}else{
return 'Windows';
}
$d = floor($cle/3600/24);
$h = floor(($cle%(3600*24))/3600);  //%取余
$m = floor(($cle%(3600*24))%3600/60);
$s = floor(($cle%(3600*24))%60);
echo "两个时间相差 $d 天 $h 小时 $m 分 $s 秒"
https://github.com/6ag/jiansan-laravel 一个简单的app后台  基于laravel,并使用dingo/api和jwt开发的一套app后台管理系统和api接口 
https://github.com/Germey/LaravelGeetest  分享极验验证码扩展包
How to create a Laravel 5 package in 10 easy steps http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/
如何開發自己的laravel Package  http://oomusou.io/laravel/laravel-package-hello-world/
Export an Eloquent Collection to a CSV with League CSV   https://mattstauffer.co/blog/export-an-eloquent-collection-to-a-csv-with-league-csv  
Route parameters – no hyphen, only underscore http://laraveldaily.com/route-parameters-no-hyphen-only-underscore/
Route::get('posts/{post_id}', function ($postId) {
    //
});
How to create a Laravel 5 package in 10 easy steps http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/
Carbon::now()->subDays(5)->diffForHumans(); 
http://laraveldaily.com/less-known-useful-carbon-functions/

filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range" => $max))); 
filter_var($int, FILTER_VALIDATE_INT,array('options' => array('min_range' => $min)));
$arr=array();

while(count($arr)<10)

{

    $arr[]=rand(1,10);

    $arr=array_unique($arr);

} sprintf("%.2f", $num);  同round
 $num = 123213.666666;  
echo sprintf("%.2f",substr(sprintf("%.3f", $num), 0, -2));  
$a= 123213.666666;
$i = 2; //保留几位
$len = pow(10,$i);
echo floor($a*$len)/$len;floor($num * 100) / 100

PHP大整数输出成科学计数法问题
$str =2228282829299292;
 //失败
echo (string)$str;  //2.2282828292993E+15  失败
echo '<br>';
echo ' '.$str; //2.2282828292993E+15
echo '<br>';
echo strval($str); //2.2282828292993E+15
echo '<br>';
 //成功
echo sprintf("%.0f", $str);
echo '<br>';
echo number_format($str);// 三位逗号分隔
高亮中文$string="I Love 黑帽联盟www.heimaolianmeng.com";
echo preg_replace("/([\x80-\xff]+)/","<font color=red>\\1</font>",$string);

if(PATH_SEPARATOR == ':'){
return 'Linux';
}else{
return 'Windows';
}
$d = floor($cle/3600/24);
$h = floor(($cle%(3600*24))/3600);  //%取余
$m = floor(($cle%(3600*24))%3600/60);
$s = floor(($cle%(3600*24))%60);
echo "两个时间相差 $d 天 $h 小时 $m 分 $s 秒"
https://github.com/6ag/jiansan-laravel 一个简单的app后台  基于laravel,并使用dingo/api和jwt开发的一套app后台管理系统和api接口 
https://github.com/Germey/LaravelGeetest  分享极验验证码扩展包
How to create a Laravel 5 package in 10 easy steps http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/
如何開發自己的laravel Package  http://oomusou.io/laravel/laravel-package-hello-world/
Export an Eloquent Collection to a CSV with League CSV   https://mattstauffer.co/blog/export-an-eloquent-collection-to-a-csv-with-league-csv  
Route parameters – no hyphen, only underscore http://laraveldaily.com/route-parameters-no-hyphen-only-underscore/
Route::get('posts/{post_id}', function ($postId) {
    //
});
How to create a Laravel 5 package in 10 easy steps http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/
Carbon::now()->subDays(5)->diffForHumans(); 
http://laraveldaily.com/less-known-useful-carbon-functions/

print  vsprintf ( "%04d-%02d-%02d" ,  explode ( '-' ,  '1988-8-1' ));  // 1988-08-01
public function boot()
    {
        \DB::listen(function($sql, $bindings, $time) {
            echo 'SQL语句执行:'.$sql.',参数:'.json_encode($bindings).',耗时:'.$time.'ms';
        });
    }

Laravel 5 路由向函数传值https://segmentfault.com/q/1010000006133260
Route::get('/{var}',function($var){
    return $var;
})->where('var','a|b|c|d|e|f|g');
Request对象也可以获取。

// URL: /portal/orders/2
public function _test(Request $request)
{
    // 1: portal
    // 2: orders
    // 3: 2
    return Request::segment(1);
}

表1有一个字段为ksort 值为1,2,3,这三个值分别对应表2中的每条数据的ID, 表2有N条数据 怎么查询能查到ksort里面值得三条数据https://segmentfault.com/q/1010000006852224
 了 select ID from 表2 where (select CONCAT(',', ksort , ',')AS ksort from 表1 ) LIKE CONCAT('%,', ID , ',%');

php的成员方法中可以写自定义函数https://segmentfault.com/q/1010000006820014 
class Test{
    public function index(){

        $hello_closures = function ($str){
            echo $str;
        };

        $hello_closures("hello , php closures function");
    }
}
static $db = null这里不是每执行一次get()就重新对$db付值为null了吗https://segmentfault.com/q/1010000006833232
class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      echo '1111';
      $db = new DatabaseConnection();
    return $db;
  }

  private function __construct()
  {
  }

}

var_dump(DatabaseConnection::get());
var_dump(DatabaseConnection::get());
因为参数是static,你在末尾对$db = new DatabaseConnection();你第二次进来的时候其实$db在第一次发生变化,所以不是null.不信你吧static换成public,应该就会出现两次
function test()
{
    static $count = 0;

    echo $count++;
    if ($count < 10) {
        test();
    }
    echo $count--;
}
前10次递归是没有执行echo $count--;的, 因为递归调用还没有结束. 直到 $count == 10的时候, 就不再进行递归了, 于是一层一层地完成递归操作

https://segmentfault.com/q/1010000006832728
namespace A{
   class A{
       static public function speak($a)
       {
           echo $a;
       }
   }

}
namespace  B{
    class B{
        static public function speak($a)
        {
            echo $a;
        }
    }

}
namespace PHP{
    use A\A;
    use B\B;
    class C{
        public static function test(){
            include "index.php";
            A::speak("I am A!");
            B::speak("I am B!");
        }
    }
    //测试
    \PHP\C::test();
}

// Store cache  
file_put_contents($cachePath, "<?phpnreturn " . var_export($myDataArray, true) . ";");  

// Retrieve cache  
$myDataArray = include($cachePath);

data:image/png;base64,
$data = explode(',', $base64_string);  

    fwrite($ifp, base64_decode($data[1])); 

if (in_array(exif_imagetype("path/to/file"), array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP))) {  
    echo "This is a picture ";  
} 

如何直接在github上预览html网页效果 http://justcoding.iteye.com/blog/2321552 
http://htmlpreview.github.io/?https://github.com/aisinvon/VerticalMiddleForUnknownHeightDiv/blob/master/Set-Unknown-Height-Div-to-Vertical-Middle.html 

PHP数组合并重组问题https://segmentfault.com/q/1010000006682621
$newArray = [];
foreach($array as $key=>$val){
    foreach($array as $k=>$v){
        if($val['job_name'] == $v['job_name'] && $val['user_name'] == $v['user_name']){
            $newArray = $val;
            $newArray['num'] = $val['num']+$v['num'];
        }
    }
}

关于正则表达式(零宽度负向断言(?!p))https://segmentfault.com/q/1010000006155587
php加密 解密 http://www.yunlu99.com/ 

if(!is_array($response) || (isset($response['code']) ^ isset($response['msg']))){
                throw new AppException('SERVER_ERROR', 500);
>>> 1^1
=> 0
>>> 1^0
=> 1
>>> 0^1
=> 1
>>> 0^0
=> 0
使用ngrok本地开发微信,代码无需上传到服务器http://www.thinkphp.cn/topic/34363.html  http://www.ngrok.cc/  
http://ngrok.2bdata.com/ 

phpcrawler,php爬虫,php采集器,多进程,多线程githubhttps://github.com/ketle/jiumozhi
[工具] 使用 Ngrok 来帮助你实现本机外网访问https://phphub.org/topics/2639
var_dump(substr_count('$re登录成sult',"登录成功"));
redis-cli monitor 此命令会记录 Redis 数据库上发生了什么操作
Linux权限管理 更改归属用户、组可以用chown命令来实现chown netcan:netcan vagrant  想要一个文件只有我能访问,其他人都不能访问chmod 700 vagrant或chmod go-rwx vagrant  chmod a+rwx vagrant-shell 以上表示所有人都有rwx权限 
\App\Models\Admin\User::where([['id',1],['name','=','lsp']])->get()
laravel 基础教程 —— 集合 collect([1, 2, 3])->all();http://www.jianshu.com/p/a6ec97b727c0
$user = User::findOrFail($id); $user->fill([
        'password' => Hash::make($request->newPassword)
      ])->save(); bcrypt('plain-text');
Crypt::encrypt($request->secret)
Redis::command('lrange', ['name', 5, 10]);   
Redis::lrange('names', 5, 10);
通过代码调用命令Artisan::call('email:send', [
    'user' => 1, '--queue' => 'default'
  ]); 
select * from tb1 order by a desc ,id desc limit 3; 用limit和order by 一个非唯一字段时,结果集并不总是确定的.已经确定为bughttp://www.codesec.net/view/213615.html

str_replace(array('%', '?'), array('%%', '%s'), '%inde?php')

str_replace(array('%', '?'), array('%%', '%s'), '%inde?php')
http://laravel-tricks.com/tricks/laravel-5-multiple-routes-files 
http://laravel-tricks.com/tricks/html-to-pdf
http://laravel-tricks.com/tricks/cancelling-a-model-save-update-delete-through-events
http://laravel-tricks.com/tricks/where-not-in-pivot-table
<script type="text/javascript">
var APP_URL = {!! json_encode(url('/')) !!};
</script>

//Then you can access that variable anywhere in your JavaScript, like so:
console.log(APP_URL);http://laravel-tricks.com/tricks/get-base-url-of-laravel-5-page-using-jquery
use Illuminate\Support\Facades\Artisan;

Artisan::call('migrate');$table->timestamp(’something_at')->default(DB::raw('CURRENT_TIMESTAMP'));
取消当前地址的POST请求的csrf_token验证http://wenda.golaravel.com/question/938 
http://laravel-tricks.com/tricks/disable-csrf-on-specific-routes
Response::json( [ "data"=> $data ], 200, [], JSON_NUMERIC_CHECK );
git clone https://github.com/CodepadME/laravel-tricks.git
$nextUserID = User::where('id', '>', $currentUser->id)->min('id');
$previousUserID = User::where('id', '<', $currentUser->id)->max('id');
Artisan::call('db:seed');https://github.com/CodepadME/laravel-tricks
array_combine方法影响了原数组https://segmentfault.com/q/1010000006131447
在foreach循环中,以引用方式遍历数组,当循环结束时,$title指向了$arrTitle的最后一组元素。

由于PHP没有块级作用域,在$title = array_combine($arr1, $arr2),之后这个$title同时修改了它指向的$arrTitle的最后一组元素,由此产生了bug
>>> date('Y-m-d H:i:s',strtotime('3600 months'));
=> "1970-01-01 00:00:00"

Packalyst is a directory of Packages for your Laravel projectshttp://packalyst.com/
if(in_array(100,$arr)) || if(in_array(101,$arr)) 
$search=[95,106,113,102,110];
$tp=array_diff($tmp_thread,$search);
if(count($tp)<count($tmp_thread)){
    ......
}
$search=[95,106,113,102,110];
$tp1=array_merge($tmp_thread,$search);
$tp2=array_flip(array_flip($tp1));
if(count($tp2)<count($tp1)){
    ......
}

function get_order_sn()
{

mt_srand((double) microtime() * 100000); 

 Vue.Js 技术栈学习分享的视频http://www.bilibili.com/video/av5788245/ 
return ‘i' . date('Ym') . str_pad(mt_rand(1, 999999), 5, '0', STR_PAD_LEFT); 
}
《手把手教你简单妹子图爬虫》系列 http://v2ex.com/t/299183#reply14 
Calculate the Max/Min value from an arrayhttp://www.jstips.co/en/calculate-the-max-min-value-from-an-array/

微信机器人小助手githubhttps://github.com/stonexer/wechatBot  http://v2ex.com/t/258230   http://www.0xroot.cn/demo.html 

可能是你的帐号不允许从远程登陆,只能在localhost。这个时候只要在localhost的那台电脑,登入mysql后,更改 "mysql" 数据库里的 "user" 表里的 "host" 项,从"localhost"改成"%" GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'mypassword' WITH
      GRANT OPTION;  
  2.FLUSH   PRIVILEGES; 

1.如果是call,apply,with,指定的this是谁,就是谁 
2.普通的函数调用,函数被谁调用,this就是谁
默认this是本对象的意思。

但是javascript里面的function有两个特殊方法call和apply,他们地一个变量,就是function内部的this,javascript里面的叫法是上下文。
this 永远指向函数运行时所在的对象,而不是函数被创建时所在的对象。
匿名函数或不处于任何对象中的函数指向 window

document.querySelector('.field').select();
document.execCommand('copy');console.log(foo+'') && false打印函数到控制台,函数执行次数
const dateTime = +new Date('2012-06-08');
const timestamp = Math.floor(dateTime / 1000);
if (document.readyState === 'complete') {
  // 页面已完全加载
}var numbers = [1, 2, 3, 4];
Math.max(...numbers) // 4
var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]];
var myNewArray = [].concat.apply([], myArray);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
var variable2 = variable1  || '';d **= 2; // d = d ** 2;
var myObject = new Map();
myObject.set('z', 1);

myObject.set('@', 2);
myObject.set('b', 3);
for (var [key, value] of myObject) {
  console.log(key, value);使对象属性有顺序
!!"hello" // true
var fibonacci = function(n){
    return n < 2 ? n : fibonacci(n-1) + fibonacci(n-2);
}dog&&dog.bark();   // This will only call dog.bark(), if dog is defined

var filteredAndSortedKeywords = keywords
  .filter(function (keyword, index) {
      return keywords.lastIndexOf(keyword) === index;
    })
  .sort(function (a, b) {
      return a < b ? -1 : 1;
    });list.length = 0;
var one = 1;
var two = 2;
var three = '3';

var result = ''.concat(one, two, three); //"123"
'something'.includes('thing'); // trueconsole.log(`My name is ${firstName} ${lastName}`);
const nodelist = [...document.querySelectorAll('div')]; // 返回一个真正的数组
(cos0+cos0+cos0)!=6 (1+1+1)!=6 2+2+2=6 3*3-3=6 √4+√4+√4=6 5+5/5=6 6+6-6=6 7-7/7=6 8-√√8+8=6 √9*√9-√9=6
关于php session 有效期 的一点疑问https://segmentfault.com/q/1010000006910375

PHP PDO 预处理是怎么缓存的https://segmentfault.com/q/1010000006906259
php计算字符串截取的问题https://segmentfault.com/q/1010000006885988
php递归组合排列函数
https://segmentfault.com/q/1010000006893377

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 . "\n";
        } else {
            recursion($groups, $rEcho);
        }
    }
}

recursion(explode(',', '123,45,6789'));
$text = '123456';
$charLength = 10; //字符串长度
$content = mb_strlen($text, 'UTF-8') <= $charLength ? $text : mb_substr($text, 0,$charLength,'UTF-8') . '...';

有一个叫rtmpdump的软件可以下载,https://segmentfault.com/q/1010000006141534   http://rtmpdump.mplayerhq.hu/   rtmpdump -r rtmp://218.28.177.199:1935/od2/mp4/sd/20160727092517877544/720p.mp4 -o m.mp4

SUM(`fee`) AS `income`, SUM(IF(`type`=5, `fee`, 0)) AS `reward`

用 python 代码讲正则的开放课件 github: https://github.com/gshmu/regex_slide  http://45.78.38.197/ss/regex/regex.html 

 Python的新浪微博爬虫https://github.com/Kevinsss/weibo_spider  
Laravel 单用户登录https://laravel-china.org/topics/2929

php,mail发送带有csv附件,下载打开后内容文字显示乱码求解决

//CSV的Excel支持GBK编码,一定要转换,否则乱码
$content = iconv('utf-8', 'gbk//ignore', $content);
foreach($dataArr as $key =>  $value){
    foreach ($value as $k1 => $v1){
         $value[$k1] = iconv('utf-8', 'gbk//ignore', $v1);
     }
    fputcsv($fh, $value);
} 
fclose($fh);
php正则表达式preg_match为什么有时候会return false?https://segmentfault.com/q/1010000006927247 
PHP随机数怎么字母加数字组合,前两个是字母后边是数字https://segmentfault.com/q/1010000006940177
unction getRandomString($prefixLength = 2, $suffixLength = 6) {
    $t = '';
    for ($i=0; $i<$prefixLength; $i++) {
        $salt = mt_rand(1000, 9999);
        if ($salt % 2) {
            $t .= chr(mt_rand(97,122));
        } else {
            $t .= chr(mt_rand(65,90));
        }
    }
    $min = intval(str_pad('1', $suffixLength, '0', STR_PAD_RIGHT));
    $max = intval(str_repeat('9', $suffixLength));
    return $t . mt_rand($min, $max);
}
简单的算法https://segmentfault.com/q/1010000006931277
$boundary = 12000;
$max_depth = 3;
$total = 0;
foreach($uids as $uid) {
    if($max_depth>0) {
        if($amounts[$uid] >= $boundary) {
            --$max_depth;
        }
        $max_depth && $total += $amounts[$uid];
    }
}
echo $total;
三维数怎么合并子数组https://segmentfault.com/q/1010000006951045

$result_arr = array();
foreach($arr as $key => $data){
    foreach($data as $val) {
        $second_key = key($val);
        $result_arr[$key][$second_key] = $val[$second_key];
    }
}
php字符串截取 https://segmentfault.com/q/1010000006948377
function pure_cut($str, $len) {
    $reg = '/' . str_repeat('[^<>]((?:<[^>]+>)+)?', $len) . '$/u';
    $str = preg_replace_callback($reg, function($matches) {
        array_shift($matches);
        $replace = join('', $matches);
        return $replace;
    }, $str, 7);
    return $str;
}

echo pure_cut($str, 7);

PHP命名空间的加载问题https://segmentfault.com/q/1010000006971418
查出缺少的那条数据https://segmentfault.com/q/1010000006953477

第一个
select t.id from (select @rownum:=@rownum+1 no,id  from table, 
(SELECT @rownum:=0) r)t where t.no - t.id = 1 limit 1
第二个
select t.id from (select @rownum:=@rownum+1 no,id  from table, 
(SELECT @rownum:=0) r)t where t.no - t.id = 2 limit 1
never use '+1 month' and '-1 month' in strtotime. It's just bugged 
>>> date('Y-m-28',  strtotime("2016-12-31 -1 month"))
=> "2016-12-28"
>>> date('Y-m-28',  strtotime("2016-01-31 +1 month"))
=> "2016-03-28"
>>> date('Y-m-d',  strtotime("2016-01-31 first day of +1 month"))
=> "2016-02-01"
$d = new DateTime('2015-01-31');
$d->modify('first day of next month');
echo $d->format('Y-m-28');https://osmosee.wordpress.com/2015/04/24/using-1-month-with-strtotime-function-in-php/

MySQL: DATE_ADD('2011-01-31', INTERVAL 1 MONTH) returns 2011-02-28 or
$the_date = strtotime('31.01.2011');
echo date('r', strtotime('last day of next month', $the_date));
http://stackoverflow.com/questions/7119777/php-strtotime-1-month-behaviour 
>>> $b=79.99
=> 79.99
>>> floor($b*100)
=> 7998.0
>>> floor(bcmul($b,100))
=> 7999.0
>>> floor(round($b*100))
=> 7999.0 https://osmosee.wordpress.com/2015/04/24/using-1-month-with-strtotime-function-in-php/
$d = new DateTime('2015-01-31');
$d->modify('first day of next month');
echo $d->format('Y-m-28');http://stackoverflow.com/questions/1211824/php-strtotime-1month-2month
https://derickrethans.nl/obtaining-the-next-month-in-php.html 

软删除 use Illuminate\Database\Eloquent\SoftDeletes;class Webinars extends Model
{
    use SoftDeletes;
public function gift()
    {
        return $this->belongsTo("App\Models\Gift", 'target_id', 'id')->withTrashed();
    }
Orders::with('gift')->where()

$restult=orders::where()

$giftIds = array_column($result, 'target_id');
       $gifts = Gift::withTrashed()->whereIn('id', $giftIds)->get()->toArray();
        $gifts = array_column($gifts, null, 'id');
         foreach ($result as $key => &$value) {
           if (isset($gifts[$value['target_id']])) {
                $value['gift_id'] = $value['target_id'];
               $value['gift_name'] = $gifts[$value['target_id']]['name'];
                $value['img_url'] = format_upload_file_path($gifts[$value['target_id']]['img_url'], 'size=640x360');
            } else {
                $value['gift_id'] = 0;
                $value['gift_name'] = '红包';
                $value['img_url'] = '';
           }
PHP GD库绘制图像,如使用imagepng()函数图像不能显示问题 private function outPut()
    {
        ob_clean();  // 我们需要先清空缓冲区
        header('Content-type:image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }
http://www.zhoujiping.com/notes/imagespng.html
http://www.hoohack.me/2016/05/31/php-source-code-count
$arr2 = array('apple', 'banana', array('cat', 'camel'), 'dog');
$val2_1 = count($arr2); // 4
$val2_2 = count($arr2, 1); // 6

array_keys(array_flip($arr))  array_merge(array_flip(array_flip($arr)))
PHP的数组保存元素的顺序是根据元素插入的顺序来保存的。,而不是索引顺序
在没有使用AUTO_INCREMENT约束的表中,或者ID是自己生成的唯一ID,lastInsertId函数返回的都是0。 
在PDO执行了excecute之后,调用PDO实例的rowCount函数可以得到执行之后的影响行数,如果结果非0,那么说明数据库插入操作执行成功了http://www.hoohack.me/2016/01/19/the-reason-why-lastInsertId-return-0

laravel软删除 use Illuminate\Database\Eloquent\SoftDeletes;class Webinars extends Model
{
    use SoftDeletes;
public function gift()
    {
        return $this->belongsTo("App\Models\Gift", 'target_id', 'id')->withTrashed();
    }
Orders::with('gift')->where()

$restult=orders::where()
$giftIds = array_column($result, 'target_id');
-        $gifts = Gift::withTrashed()->whereIn('id', $giftIds)->get()->toArray();
-        $gifts = array_column($gifts, null, 'id');
         foreach ($result as $key => &$value) {
-            if (isset($gifts[$value['target_id']])) {
-                $value['gift_id'] = $value['target_id'];
-                $value['gift_name'] = $gifts[$value['target_id']]['name'];
-                $value['img_url'] = format_upload_file_path($gifts[$value['target_id']]['img_url'], 'size=640x360');
-            } else {
-                $value['gift_id'] = 0;
-                $value['gift_name'] = '红包';
-                $value['img_url'] = '';
-            }

function array_sum_with_key(array $arr1, array $arr2, array $_ = null)
{
    $args = array_slice(func_get_args(), 1);

    foreach ($args as $arr) {
        foreach ($arr as $k => $v) {
            if (isset($arr1[$k])) {
                $arr1[$k] += $v;
            } else {
                $arr1[$k] = $v;
            }
        }
    }

    return $arr1;
}
$start = new DateTime('2016-09-15');
$end =  new DateTime('2016-09-17');

for ($start;$start<=$end;$start->modify('+1 day')) {
   echo $start->format('Y-m-d')."<br/>";
} 

mysql 如何实现先排序后分组
1、可以先把数据按照你的条件要求,使用order by排好序
2、在查询sql外面,再包一层查询,使用group by
例如: select * from (select * from t where 你的查询条件 order by 你的排序字段) group by 你的分组字段 http://sunny90.com/a/database/2014/0909/129.html
UPDATE mytable SET title = CASE
WHEN id = 1 THEN 'Great Expectations';
WHEN id = 2 THEN 'War and Peace';
ELSE title
END;
UPDATE mytable SET title = CASE
WHEN id = 1 THEN ‘Great Expectations’
WHEN id = 2 THEN ‘War and Peace’
...
END
WHERE id IN (1,2,...)
//在数组$a的第n个元素的位置上插入$p,原来的第n位以以后往后移。
//$p如果是个数组就是支持2维数组了。
$n=2;$p=[1,2,3];$a=[4,7,9];
array_splice($a, $n-1, 0, $p);
var_dump($a);

$arr = [['a' , 'b'] , ['c' , 'd']];
var_dump(array_combine(array_column($arr, 0) , array_column($arr, 1)));

curl -i -H 'content-type: application/json' -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}' http://localhost:3570/index.php   curl_setopt($ch, CURLOPT_HTTPHEADER, array(                   
    'Content-Type: application/json',  
    'Content-Length: ' . strlen($data_string))           
);  $.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})\DB::listen(function($sql,$query){
            dump($sql,$query);
        }); 
Response::json($result)->setCallback(Input::get('callback'));
Response::json($result, 200, array('Content-Type' => 'application/javascript'));
\laravel_web\bootstrap\app.php
$app['events']->listen('illuminate.query', function($sql, $binds) use ($app){
    $connName = config('database.default');
    dump($connName,$sql, $binds);
    //$app['db']->purge($connName);
    //\DB::purge($connName);
    //\DB::disconnect($connName);
});

设置 cookie,$cookie 是一个字符串
curl_setopt($ch, CURLOPT_COOKIE, $cookie); 也可以通过文件的形式将 cookie 写入:curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
 '.'在默认情况下匹配的是除了换行符的所有字符, 而不是"所有非空字符"

解决方案有两种, 第一个正是 @jsoncode 提供的

([\s\S]*?)

第二种是给正则表达式添加模式修饰符 /s, 这样 . 就是匹配所有字符了

/<body>(.*)<\/body>/s
lovecn commented 7 years ago

https://segmentfault.com/q/1010000006866791 $arr= array( '1'=>array('id'=>1, 'pid'=>0,), '2'=>array('id'=>2, 'pid'=>0,), '3'=>array('id'=>3, 'pid'=>1,), '4'=>array('id'=>4, 'pid'=>2,), '5'=>array('id'=>5, 'pid'=>4), '6'=>array('id'=>6, 'pid'=>5,), '7'=>array('id'=>7, 'pid'=>3), '8'=>array('id'=>8, 'pid'=>4,), '9'=>array('id'=>9, 'pid'=>7), );

//以ID为键值格式化 foreach ($arr as $key => $value) { $list[$value['id']]=$value; }

//遍历数组 foreach ($list as $key => $value) { if($value['pid']==0){ $tree[$value['id']]=$value;

}else{
    //祖先ID
    $ancestor_id='';
    //判断祖先数组里面有没有对应的值,有则取出
    if(!empty($ancestor[$value['pid']])){
        $ancestor_id=$ancestor[$value['pid']];

    }else{

        $topid=$value['id'];
        $child=array();
        if(empty($ancestor[$topid])){
            $child[]=$topid;
        }
        //通过循环,一层一层的往上找,找出他们各自的父亲,直到祖宗为止
        while($list[$topid]['pid'] > 0)
        {

                $topid = $list[$topid]['pid'];    

                if(empty($topid)){
                    $topid='';
                    break;

                }else{

                    //祖宗数组里面没有,则放入子孙数组
                    if(empty($ancestor[$topid])){
                        $child[]=$topid;
                    }else{
                        //祖先已经存在,就不用循环下去了
                        $topid=$ancestor[$topid];
                        break;

                    }

                }

        }

        $ancestor_id= $topid;
        //如果找到祖宗,就将子孙数组对应加入到祖宗数组里面
        if(!empty($ancestor_id)){
            foreach ($child as $k => $v) {
                $ancestor[$v]=$ancestor_id;
            }

        }

    }
    if(!empty($ancestor_id)){
        $tree[$ancestor_id]['child'][$value['id']]=$value;

    }

}

} echo '

';
var_dump($tree);
Array
(
[1] => Array
(
[id] => 1
[pid] => 0
[child] => Array
(
[3] => Array
(
[id] => 3
[pid] => 1
)

                [7] => Array
                    (
                        [id] => 7
                        [pid] => 3
                    )

                [9] => Array
                    (
                        [id] => 9
                        [pid] => 7
                    )

            )

    )

[2] => Array
    (
        [id] => 2
        [pid] => 0
        [child] => Array
            (
                [4] => Array
                    (
                        [id] => 4
                        [pid] => 2
                    )

                [5] => Array
                    (
                        [id] => 5
                        [pid] => 4
                    )

                [6] => Array
                    (
                        [id] => 6
                        [pid] => 5
                    )

                [8] => Array
                    (
                        [id] => 8
                        [pid] => 4
                    )

            )

    )

)

lovecn commented 7 years ago

Array ( [0] => Array ( [id] => 1 [name] => 代码 [parent] => 0 )

[1] => Array
    (
        [id] => 3
        [name] => 动漫
        [parent] => 0
    )

[2] => Array
    (
        [id] => 4
        [name] => 治愈
        [parent] => 3
    )

[3] => Array
    (
        [id] => 5
        [name] => 励志
        [parent] => 3
    )

[4] => Array
    (
        [id] => 6
        [name] => 机战
        [parent] => 3
    )

[5] => Array
    (
        [id] => 7
        [name] => 百合
        [parent] => 3
    )

[6] => Array
    (
        [id] => 8
        [name] => 资源
        [parent] => 0
    )

[7] => Array
    (
        [id] => 9
        [name] => app
        [parent] => 8
    )

[8] => Array
    (
        [id] => 10
        [name] => 软件
        [parent] => 8
    )

[9] => Array
    (
        [id] => 11
        [name] => 黑科技
        [parent] => 8
    )

) https://segmentfault.com/q/1010000007011243 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) );

lovecn commented 7 years ago

在php5,一个对象变量已经不再保存整个对象的值。只是保存一个标识符来访问真正的对象内容。 当对象作为参数传递,作为结果返回,或者赋值给另外一个变量,另外一个变量跟原来的不是引用的关系,只是他们都保存着同一个标识符的拷贝,这个标识符指向同一个对象的真正内容。 class A{ public $num=100; } $a = new A(); $b = $a; $a->num=200; echo $b->num;//200 对象的复制是通过引用来实现的,$a=new A();$b=$a;相当于$a=new A();$b=&$a;

lovecn commented 7 years ago

php 奇葩 0=='0' //true 0 == 'abcdefg' //true 0 === 'abcdefg' //false 1 == '1abcdef' //true "0e132456789"=="0e7124511451155" //true "0e123456abc"=="0e1dddada" //false "0e1abc"=="0" //true

"0x1e240"=="123456" //true "0x1e240"==123456 //true "0x1e240"=="1e240" //false 如果switch是数字类型的case的判断时,switch会将其中的参数转换为int类型

$i ="2abc"; switch ($i) { case 0: case 1: case 2: echo "i is less than 3 but not negative"; break; case 3: echo "i is 3"; } $array=[0,1,2,'3']; var_dump(in_array('abc', $array)); //true var_dump(in_array('1bc', $array)); //true var_dump(intval('2')) //2 var_dump(intval('3abcd')) //3 var_dump(intval('abcd')) //0 if(intval($a)>1000) { mysql_query("select * from news where id=".$a) } $array1[] = array( "foo" => "bar", "bar" => "foo", ); $array2 = array("foo", "bar", "hello", "world"); var_dump(md5($array1)==var_dump($array2)); //true 传递一个array时,md5()不会报错,知识会无法正确地求出array的md5值,这样就会导致任意2个array的md5值都会相等。