2020-07-28 18:10:00
围观(3675)
将数据进行按年月分组的需求其实挺常见的, 例如支付宝 / 微信的账单就有按年月组合.
假设从数据库中查询出来的结果:
$data = [ [ 'id' => 1, 'name' => '1', 'content' => '1', 'created_at' => '2020-06-28 15:00:00' ], [ 'id' => 2, 'name' => '2', 'content' => '2', 'created_at' => '2020-07-02 15:00:00' ], [ 'id' => 3, 'name' => '3', 'content' => '3', 'created_at' => '2020-07-28 18:00:00' ] ];
此时直接转为 JSON 是这样的:
[ { "id": 1, "name": "1", "content": "1", "created_at": "2020-06-28 15:00:00" }, { "id": 2, "name": "2", "content": "2", "created_at": "2020-07-02 15:00:00" }, { "id": 3, "name": "3", "content": "3", "created_at": "2020-07-28 18:00:00" } ]
先写一个可以将数据转为按月组合的方法:
function monthlyGrouping($arr_data, $time_field = 'created_at') { if (empty($time_field)) { return $arr_data; } // 按月份分组 $arr_month = []; $arr_year_month = []; // 全部年月数据 $arr_return_data = []; foreach ($arr_data as $data) { // 按月份分组 $year_month = mb_substr($data[$time_field], 0, 7); $arr_month[$year_month]['lst_month_data'][] = $data; if (!isset($arr_year_month[$year_month])) { $arr_year_month[$year_month] = $year_month; } if (!isset($arr_month[$year_month]['obj_month_info'])) { $arr_month[$year_month]['obj_month_info'] = [ 'year' => mb_substr($year_month, 0, 4), 'month' => mb_substr($year_month, 5, 2), ]; } } foreach ($arr_month as $key => $month) { $arr_return_data[] = $arr_month[$key] ?? []; } return $arr_return_data; }
此时执行该方法:
$data = [ [ 'id' => 1, 'name' => '1', 'content' => '1', 'created_at' => '2020-06-28 15:00:00' ], [ 'id' => 2, 'name' => '2', 'content' => '2', 'created_at' => '2020-07-02 15:00:00' ], [ 'id' => 3, 'name' => '3', 'content' => '3', 'created_at' => '2020-07-28 18:00:00' ] ]; $lst_return = monthlyGrouping($data, 'created_at'); exit(json_encode($lst_return));
输出的结果:
[ { "lst_month_data": [ { "id": 1, "name": "1", "content": "1", "created_at": "2020-06-28 15:00:00" } ], "obj_month_info": { "year": "2020", "month": "06" } }, { "lst_month_data": [ { "id": 2, "name": "2", "content": "2", "created_at": "2020-07-02 15:00:00" }, { "id": 3, "name": "3", "content": "3", "created_at": "2020-07-28 18:00:00" } ], "obj_month_info": { "year": "2020", "month": "07" } } ]
方法的 created_at 可以传递指定的字段, 就是数据的时间字段不一定是 created_at 也可以使用.
本文地址 : bubaijun.com/page.php?id=202
版权声明 : 未经允许禁止转载!
上一篇文章: 博客被反代了 真的太难了
下一篇文章: PHP获取指定日期的开始及结束时间