搜尋

首頁  >  問答  >  主體

Laravel 根據年份值組合多維數組

這是我想要根據年份值組合的陣列

0 => array:3 [▼
    "year" => 2022
    "total_policies_financed" => 1
    "total_amount_financed" => 280.0
  ]
  1 => array:3 [▼
    "year" => 2022
    "total_policies_financed" => 2
    "total_amount_financed" => 5190.0
  ]
  2 => array:3 [▼
    "year" => 2021
    "total_policies_financed" => 2
    "total_amount_financed" => 5190.0
  ]

需要這樣的輸出

#
0 => array:3 [▼
    "year" => 2022,
    "total_count" => 2,
    "total_policies_financed" => 3
    "total_amount_financed" => 5470
  ]
  1 => array:3 [▼
   "year" => 2021,
    "total_count" => 1,
    "total_policies_financed" => 2
    "total_amount_financed" => 5190.0
  ]

P粉193307465P粉193307465326 天前390

全部回覆(1)我來回復

  • P粉633075725

    P粉6330757252024-02-18 18:25:28

    試試這個:

    $arr = collect($array)->groupBy('year')->map(function ($items, $key){
        return [
            'year' => $key,
            'total_count' => $items->count(),
            'total_policies_financed' => $items->sum('total_policies_financed'),
            'total_amount_financed' => $items->sum('total_amount_financed'),
        ];
    })->values();
    
    dd($arr);

    回覆
    0
  • 取消回覆