I want to make a result from query after distinct and groupby
This is My Code
$results = DB::table('dokumen')
->join('pengadaan', 'dokumen.id_jenis_pengadaan', '=', 'pengadaan.id')
->select(
DB::raw('COUNT(nama_paket) AS jml'),
DB::raw('jenis_pengadaan as jenis_pengadaan'),
DB::raw('tahun as tahun')
)
->groupBy('jenis_pengadaan', 'tahun')
->orderBy('tahun')
->get();
$hasil = [];
foreach ($results as $result) {
$kategori = $result->jenis_pengadaan;
$jml = $result->jml;
$hasil[] = [
'tahun' => $result->tahun,
'kategori_paket' => $kategori,
'jml' => $jml,
];
}
dd($hasil);
And This is The Results of My Code
array:12 [▼ // app/Http/Controllers/HomeController.php:51
0 => array:3 [▶
"tahun" => 2022
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung - Barang"
]
"jml" => array:1 [▶
0 => "9"
]
]
1 => array:3 [▶
"tahun" => 2022
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung - Konstruksi"
]
"jml" => array:1 [▶
0 => "69"
]
]
2 => array:3 [▶
"tahun" => 2022
"kategori_paket" => array:1 [▶
0 => "Tender-Konstruksi"
]
"jml" => array:1 [▶
0 => "12"
]
]
3 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung - Barang"
]
"jml" => array:1 [▶
0 => "30"
]
]
4 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung - Jasa Lainnya"
]
"jml" => array:1 [▶
0 => "17"
]
]
5 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung - Konstruksi"
]
"jml" => array:1 [▶
0 => "201"
]
]
6 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Tender-Konstruksi"
]
"jml" => array:1 [▶
0 => "25"
]
]
7 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Seleksi"
]
"jml" => array:1 [▶
0 => "5"
]
]
8 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "e-Katalog"
]
"jml" => array:1 [▶
0 => "2"
]
]
9 => array:3 [▶
"tahun" => 2023
"kategori_paket" => array:1 [▶
0 => "Pengadaan Langsung-Konsultan"
]
"jml" => array:1 [▶
0 => "14"
]
]
]
How to group the $hasil only 2 array groupby Year? so there’s only 2022 and 2023
i’ve tried everything to solve this . but i cant find the answer
hope you guys cant help me solve this
thanks . best regards
3
Answers
You could modify your loop to collect together entries that have the same
$result->tahun
value:Here’s an adjusted code:
You can simply do this inside your
foreach