关于一个归档问题?
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 协议》,转载必须注明作者和本文链接
推荐文章: