在 Laravel 中映射数据

我无法理解 Laravel 中 API 的响应,这令人困惑。


我期待这个输出


{

  "month": "January",

  "year": 2020,

  "history_data": [

    {

      "id": 27,

      "jurnal_id": 12313,

      "name": "Transaksi RAHN FLEKSI",

      "point": 500,

      "status": "SUKSES",

      "created_at": "2020-03-18 17:03:26",

      "updated_at": "2020-03-18 17:03:26",

    },

  ]

},

{

  "month": "February",

  "year": 2020,

  "history_data": [

    {

      "id": 27,

      "jurnal_id": 1231313,

      "name": "Transaksi RAHN FLEKSI",

      "point": 500,

      "status": "SUKSES",

      "created_at": "2020-03-18 17:03:26",

      "updated_at": "2020-03-18 17:03:26",

    }

  ],

  {

    "month": "February",

    "year": 2021,

    "history_data": [

      {

        "id": 182,

        "jurnal_id": 13213,

        "name": "Transaksi RAHN FLEKSI",

        "point": 500,

        "status": "SUKSES",

        "created_at": "2021-02-18 17:03:26",

        "updated_at": "2021-02-18 17:03:26",

      },

      {

        "id": 1812313,

        "jurnal_id": 12313313,

        "name": "Transaksi RAHN FLEKSI",

        "point": 500,

        "status": "SUKSES",

        "created_at": "2021-02-18 17:03:26",

        "updated_at": "2021-02-18 17:03:26",

      }

    ]

    {

    "month": "March",

    "year": 2021,

    "history_data": [

        {

        "id": 183,

        "jurnal_id": 132313,

        "name": "Transaksi RAHN FLEKSI",

        "point": 500,

        "status": "SUKSES",

        "created_at": "2021-03-18 17:03:26",

        "updated_at": "2021-03-18 17:03:26",

        }

    ]

}

如果我没记错的话,“history_data”按年和月分组。但是,我仍然得到如下回复


慕沐林林
浏览 158回答 1
1回答

有只小跳蛙

问题是 :$makeToCollection = collect($arr)->groupBy('year');该groupBy方法按给定键对集合的项目进行分组只需使用:$makeToCollection = collect($arr);顺便说一句,collection 允许你链接它的方法来执行流畅的映射和减少:$historyPoints = $this->historyPoint    ->select(        DB::raw("REGEXP_REPLACE(to_char(created_at, 'Month'), '\s+$', '') as month"),        DB::raw("date_part('Year', created_at) as year")    )    ->groupBy('year', 'month')    ->orderBy('year', 'desc')    ->get();/***** Here we go *****/$makeToCollection = $historyPoints->map(function ($item) {    $history_data = [];    foreach (HistoryPointAdd::all() as $data) {        $month = date('F', strtotime($data->created_at));        $year  = date('Y', strtotime($data->created_at));        if ($month == $historyPoint->month && $year == $historyPoint->year) {            $history_data[] = $data;        }    }    $item['history_data'] = $history_data;    return $item;});return $this->sendSuccess($this->successMessage, $makeToCollection);
打开App,查看更多内容
随时随地看视频慕课网APP