我试图按月总持续时间显示表格,所以我确实按相同时间戳的月度数据的持续时间进行排序,但我做不到。
我的目标是通过一个对象或数组值的返回值创建一个表。
public function monthlyResult(Request $request = null)
{
$user_id = Auth::user()->id;
if($request){
$year = $request->year;
$month = $request->month;
}
else{
$year = date('Y');
}
$monthlyResult = DB::table('workings')
->where('user_id', $user_id)
->whereYear('created_at', $year)
->orwhere(function ($query) use($user_id, $year) {
$query->where('user_id', $user_id)
->whereYear('deleted_at', $year);
})
->get();
foreach($monthlyResult as $mResult){
$month = date('n', strtotime($mResult->created_at));
$duration = $mResult->duration;
---- code ----
}
return ;
}
个月|总持续时间|
---- 1 --- | | xxxxxxxx |
---- 2 --- | xxxxxxxx |
---- 3 --- | xxxxxxxx |
...
--- 11 --- | xxxxxxxx |
--- 12 --- | | xxxxxxxx |
答案 0 :(得分:1)
您可以创建一个关联数组并按键排序
$results = [];
foreach($monthlyResult as $mResult){
$month = date('n', strtotime($mResult->created_at));
$results[$month] = (isset($results[$month])) ? ($results[$month] + $mResult->duration) : $mResult->duration ;
}
//now sort $results based on key
ksort($results);
如@ C2486所述,您可以使用orderBy
$monthlyResult = DB::table('workings')
->where('user_id', $user_id)
->whereYear('created_at', $year)
->orwhere(function ($query) use ($user_id, $year) {
$query->where('user_id', $user_id)
->whereYear('deleted_at', $year);
})
->orderBy(DB::raw('month(created_at)'))
->get();