array:5 [▼
0 => array:2 [▼
"year" => 2020
"month" => "December"
]
1 => array:2 [▼
"year" => 2019
"month" => "December"
]
2 => array:2 [▼
"year" => 2018
"month" => "December"
]
3 => array:2 [▼
"year" => 2018
"month" => "August"
]
4 => array:2 [▼
"year" => 2017
"month" => "December"
]
]比如在設計
產品需求:
每一年中那幾個月發表了文章,做一個歸檔統計,有沒有高效的方法?
還有什麼更好的歸檔方式
根據文章表中的created_at欄位進行年月分組 2018-08-17 16:16:30
2020
1月
文章標題1
文章標題2
......
2月
3月
...
2019
1月
2月
3月
....
2018
類似於上面這種結構
解決方案:
function initArray(array $array)
{
$newArray = [];
foreach ($array as $item) {
if (isset($newArray[$item['year']])) {
$newArray[$item['year']]['month'][] = $item['month'];
} else {
$newArray[$item['year']] = ['year' => $item['year'], 'month' => [$item['month']]];
}
}
return $newArray;
}
//使用者的文章年月歸檔
public function datearticle(User $user)
{
//獲取文章中的年月
$years_month = Article::selectRaw('year(created_at) year,monthname(created_at) month, count(*) num')
->groupBy('year','month')
->orderByRaw('min(created_at) desc')
->get();
$newArray = [];
foreach ($years_month as $item) {
if (isset($newArray[$item['year']])) {
$newArray[$item['year']]['month'][] = $item['month'];
} else {
$newArray[$item['year']] = ['year' => $item['year'], 'month' => [$item['month']]];
}
}
dd($newArray);
return view('home.user.datearticle',compact('years'));
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結