Bus*_*erX 4 php laravel laravel-5 laravel-collection
与Laravel系列合作,我的头疼.我有两个集合:
$dt = Carbon::now();
$days = new Collection([]);
/**
* Create a calender month
*/
for ($day = 1; $day <= $dt->daysInMonth; $day++) {
$date = Carbon::create($dt->year, $dt->month, $day)->toDateString();
$days->push(new Timesheet([
'date' => $date,
]));
}
/**
* Get all timesheets for user
*/
$timesheets = Timesheet::where('user_id', $this->user->id)
->get();
Run Code Online (Sandbox Code Playgroud)
\Illuminate\Database\Eloquent\Collection($timesheets)
#attributes: array:5 [?
"id" => "1"
"user_id" => "1"
"date" => "2016-02-22 22:05:01"
"created_at" => "2016-02-22 22:05:01"
"updated_at" => "2016-02-22 22:05:01"
]
// ... one or more ...
Run Code Online (Sandbox Code Playgroud)
我有第二个收藏给了我一个月的所有日子.
\Illuminate\Support\Collection($days)
#attributes: array:1 [?
"date" => "2016-02-01 00:00:00"
]
// ... and the rest of the month.
Run Code Online (Sandbox Code Playgroud)
我想将$days集合与$timesheet集合合并,保留集合的值$timesheet并删除集合中存在的任何重复项$days.E. g.如果$timesheets已经包含'2016-02-24'我并不想合并'2016-02-24'的$days.我该怎么做呢?
用途merge:
$collection1 = Model1::all();
$collection2 = Model2::all();
$mergedCollection = $collection1->merge($collection2);
Run Code Online (Sandbox Code Playgroud)
文档讨论了如何将它与数组一起使用,但是查看方法签名它将采用混合参数.在本地安装的Laravel 4项目上测试它对我有用.
好的,尝试一下。逻辑应该差不多可以解决,但 obv 无法访问您的 Timesheet 类。
$days = new Collection([]);
//basically the same structure i think
$timesheets = new Collection([new Collection(['date'=>'2016-02-23','created_at'=>'2016-02-23 14:12:34']),new Collection(['date'=>'2016-02-28','created_at'=>'2016-02-23 14:15:36'])]);
$dt = Carbon::now();
for ($day = 1; $day <= $dt->daysInMonth; $day++) {
$date = Carbon::create($dt->year, $dt->month, $day)->format('Y-m-d');
//filter your timesheets and see if there is one for this day
$timesheet = $timesheets->filter(function($timesheet) use($date){return $timesheet->get('date')==$date;});
if(!$timesheet->isEmpty()){
//if there is a timesheet for today then add it to your $days collection
$days->push($timesheet);
}else{
//otherwise just stick in the date
$days->push(new Collection([
'date' => $date,
]));
}
}
//voila!
dd($days);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2082 次 |
| 最近记录: |