Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge two collection with the same key and preserve the value

i have the following code :

$kategori = KategoriProduk::select('kategori_produks.nama as nama_kategori', 'tipe_produks.layanan as nama_tipe')
    ->leftJoin('tipe_produks', 'tipe_produks.kategori_produk_id', '=', 'kategori_produks.id')->get();

and the result is :

0 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => "A"
],
1 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => "B"
],
2 => [
   "nama_kategori" => "hobs"
   "nama_tipe" => "A"
],

and i want the result to something like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0 => [
   "nama_kategori" => "range hoods"
   "nama_tipe" => ["A", "B"]
],
1 => [
   "nama_kategori" => "hobs"
   "nama_tipe" => "A"
],

i tried using distinct() but the result isnt quite what i want.
any help is appreciated! thanks!

>Solution :

You can use groupBy like this :

$result = $kategori
    ->groupBy('nama_kategori')
    ->map(function ($items, $key) {
        // Get all 'nama_tipe' values from the grouped items
        $namaTipe = $items->pluck('nama_tipe');
        
        // If there's only one 'nama_tipe', return it as a string, otherwise return as an array
        return [
            'nama_kategori' => $key,
            'nama_tipe' => $namaTipe->count() === 1 ? $namaTipe->first() : $namaTipe->all()
        ];
    })
    ->values();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading