Repositori ini berisi beberapa makro koleksi yang berguna.
Spatie adalah agen desain web yang berbasis di Antwerpen, Belgia. Anda akan menemukan ikhtisar semua proyek sumber terbuka kami di situs web kami.
Kami menginvestasikan banyak sumber daya untuk menciptakan paket sumber terbuka terbaik di kelasnya. Anda dapat mendukung kami dengan membeli salah satu produk berbayar kami.
Kami sangat menghargai Anda mengirimi kami kartu pos dari kota asal Anda, yang menyebutkan paket kami mana yang Anda gunakan. Anda akan menemukan alamat kami di halaman kontak kami. Kami mempublikasikan semua kartu pos yang diterima di dinding kartu pos virtual kami.
Anda dapat menarik paket melalui composer:
composer require spatie/laravel-collection-macrosPaket akan otomatis mendaftar sendiri.
afteratsecondthirdfourthfifthsixthseventheighthninthtenthgetNthbeforecatchchunkBycollectBycontainsAnycontainsAlleachConsextractfilterMapfirstOrFailfirstOrPushfromPairsgetCaseInsensitiveglobgroupByModelhasCaseInsensitiveheadififAnyifEmptyinsertAfterinsertAfterKeyinsertAtinsertBeforeinsertBeforeKeynonepaginatepathpluckManypluckManyValuespluckToArrayprioritizerecursiverotatesectionBysimplePaginatesliceBeforetailtrytoPairstransposevalidateweightedRandomwithSizeafterDapatkan item berikutnya dari koleksi.
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 2 ;
$ currentItem = $ collection -> after ( $ currentItem ); // return 3;
$ collection -> after ( $ currentItem ); // return null;
$ currentItem = $ collection -> after ( function ( $ item ) {
return $ item > 1 ;
}); // return 3;Anda juga dapat meneruskan parameter kedua untuk digunakan sebagai cadangan.
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 3 ;
$ collection -> after ( $ currentItem , $ collection -> first ()); // return 1;atAmbil item di indeks.
$ data = new Collection ([ 1 , 2 , 3 ]);
$ data -> at ( 0 ); // 1
$ data -> at ( 1 ); // 2
$ data -> at (- 1 ); // 3secondAmbil item di indeks kedua.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> second (); // 2thirdAmbil item di indeks ketiga.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> third (); // 3fourthAmbil item di indeks keempat.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fourth (); // 4fifthAmbil item di indeks kelima.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fifth (); // 5sixthAmbil item di indeks keenam.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> sixth (); // 6seventhAmbil item di indeks ketujuh.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> seventh (); // 7eighthAmbil item di indeks kedelapan.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> eighth (); // 8ninthAmbil item di indeks kesembilan.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> ninth (); // 9tenthAmbil item di indeks kesepuluh.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> tenth (); // 10getNthAmbil item di item ke-n.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ]);
$ data -> getNth ( 11 ); // 11beforeDapatkan item sebelumnya dari koleksi.
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 2 ;
$ currentItem = $ collection -> before ( $ currentItem ); // return 1;
$ collection -> before ( $ currentItem ); // return null;
$ currentItem = $ collection -> before ( function ( $ item ) {
return $ item > 2 ;
}); // return 2;Anda juga dapat meneruskan parameter kedua untuk digunakan sebagai cadangan.
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 1 ;
$ collection -> before ( $ currentItem , $ collection -> last ()); // return 3;catch Lihat Try
chunkBy Memotong nilai-nilai dari koleksi menjadi beberapa kelompok selama panggilan balik yang diberikan benar. Jika parameter opsional $preserveKeys sebagai true diteruskan, kunci asli akan dipertahankan.
collect ([ ' A ' , ' A ' , ' B ' , ' A ' ])-> chunkBy ( function ( $ item ) {
return $ item == ' A ' ;
}); // return Collection([['A', 'A'],['B'], ['A']])collectByDapatkan item dengan kunci tertentu, dan kumpulkan.
$ collection = collect ([
' foo ' => [ 1 , 2 , 3 ],
' bar ' => [ 4 , 5 , 6 ],
]);
$ collection -> collectBy ( ' foo ' ); // Collection([1, 2, 3])Anda juga dapat meneruskan parameter kedua untuk digunakan sebagai cadangan.
$ collection = collect ([
' foo ' => [ 1 , 2 , 3 ],
' bar ' => [ 4 , 5 , 6 ],
]);
$ collection -> collectBy ( ' baz ' , [ ' Nope ' ]); // Collection(['Nope'])containsAny Akan mengembalikan true jika satu atau lebih nilai yang diberikan ada dalam koleksi.
$ collection = collect ([ ' a ' , ' b ' , ' c ' ]);
$ collection -> containsAny ([ ' b ' , ' c ' , ' d ' ]); // returns true
$ collection -> containsAny ([ ' c ' , ' d ' , ' e ' ]); // returns true
$ collection -> containsAny ([ ' d ' , ' e ' , ' f ' ]); // returns false
$ collection -> containsAny ([]); // returns falsecontainsAll Akan mengembalikan true jika semua nilai yang diberikan ada dalam koleksi.
$ collection = collect ([ ' a ' , ' b ' , ' c ' ]);
$ collection -> containsAll ([ ' b ' , ' c ' ,]); // returns true
$ collection -> containsAll ([ ' c ' , ' d ' ]); // returns false
$ collection -> containsAll ([ ' d ' , ' e ' ]); // returns false
$ collection -> containsAll ([]); // returns trueeachCons Dapatkan tetangga berturut-turut berikut dalam koleksi dari ukuran potongan tertentu. Jika parameter opsional $preserveKeys sebagai true diteruskan, kunci asli akan dipertahankan.
collect ([ 1 , 2 , 3 , 4 ])-> eachCons ( 2 ); // return collect([[1, 2], [2, 3], [3, 4]])extract Ekstrak kunci dari koleksi. Ini sangat mirip dengan only , dengan dua perbedaan utama:
extract mengembalikan larik nilai, bukan larik asosiatifnull alih-alih menghilangkannya extract berguna saat menggunakan sintaks PHP 7.1 short list() .
[ $ name , $ role ] = collect ( $ user )-> extract ( ' name ' , ' role.name ' );filterMapPetakan koleksi dan hapus nilai palsu sekaligus.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ])-> filterMap ( function ( $ number ) {
$ quotient = $ number / 3 ;
return is_integer ( $ quotient ) ? $ quotient : null ;
});
$ collection -> toArray (); // returns [1, 2]firstOrFail Dapatkan item pertama. Melempar SpatieCollectionMacrosExceptionsCollectionItemNotFound jika item tidak ditemukan.
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ])-> firstOrFail ();
$ collection -> toArray (); // returns [1]
collect ([])-> firstOrFail (); // throws SpatieCollectionMacrosExceptionsCollectionItemNotFoundfirstOrPushAmbil item pertama menggunakan callable yang diberikan sebagai parameter pertama. Jika tidak ada nilai, masukkan nilai parameter kedua ke dalam koleksi. Anda dapat meneruskan callable sebagai parameter kedua.
Metode ini sangat berguna ketika berhadapan dengan properti kelas yang di-cache, di mana Anda ingin menyimpan nilai yang diambil dari API atau fungsi komputasi yang mahal dalam koleksi untuk digunakan beberapa kali.
$ collection = collect ([ 1 , 2 , 3 ])-> firstOrPush ( fn ( $ item ) => $ item === 4 , 4 );
$ collection -> toArray (); // returns [1, 2, 3, 4]Kadang-kadang, Anda ingin menentukan koleksi target yang akan dituju. Anda dapat meneruskan ini sebagai parameter ketiga.
$ collection = collect ([ 1 , 2 , 3 ]);
$ collection -> filter ()-> firstOrPush ( fn ( $ item ) => $ item === 4 , 4 , $ collection );
$ collection -> toArray (); // returns [1, 2, 3, 4]fromPairsUbah koleksi menjadi item koleksi bentuk array asosiatif.
$ collection = collect ([[ ' a ' , ' b ' ], [ ' c ' , ' d ' ], [ ' e ' , ' f ' ]])-> fromPairs ();
$ collection -> toArray (); // returns ['a' => 'b', 'c' => 'd', 'e' => 'f']getCaseInsensitiveDapatkan nilai kunci tertentu.
Jika kuncinya adalah string, kami akan mencari kunci tersebut menggunakan perbandingan yang tidak peka huruf besar-kecil.
$ collection = collect ([
' foo ' => ' bar ' ,
]);
$ collection -> getCaseInsensitive ( ' Foo ' ); // returns 'bar';glob Mengembalikan kumpulan hasil glob() .
Collection:: glob ( ' config/*.php ' );groupByModel Mirip dengan groupBy , tetapi mengelompokkan koleksi berdasarkan model Eloquent. Karena kuncinya adalah objek, bukan bilangan bulat atau string, hasilnya dibagi menjadi array terpisah.
$ posts -> groupByModel ( ' category ' );
// [
// [$categoryA, [/*...$posts*/]],
// [$categoryB, [/*...$posts*/]],
// ]; Tanda tangan lengkap: groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)
hasCaseInsensitiveTentukan apakah koleksi berisi kunci dengan nama tertentu.
Jika $key adalah string, kami akan mencari kunci menggunakan perbandingan yang tidak peka huruf besar-kecil.
$ collection = collect ([
' foo ' => ' bar ' ,
]);
$ collection -> hasCaseInsensitive ( ' Foo ' ); // returns true;headMengambil item pertama dari koleksi.
$ collection = collect ([ 1 , 2 , 3 ]);
$ collection -> head (); // return 1
$ collection = collect ([]);
$ collection -> head (); // return nullif Makro if dapat membantu rantai pengumpulan cabang. Ini adalah tanda tangan makro ini:
if (mixed $ if , mixed $ then = null , mixed $ else = null ): mixed $if , $then dan $else dapat berupa jenis apa pun. Jika penutupan diteruskan ke salah satu parameter ini, maka penutupan tersebut akan dieksekusi dan makro akan menggunakan hasilnya.
Ketika $if mengembalikan nilai yang sebenarnya, maka $then akan dikembalikan, jika tidak, $else akan dikembalikan.
Berikut beberapa contohnya:
collect ()-> if ( true , then: true , else: false ); // returns true
collect ()-> if ( false , then: true , else: false ); // returns false Ketika penutupan diteruskan ke $if , $then atau $else , seluruh koleksi akan diteruskan sebagai argumen untuk penutupan tersebut.
// the `then` closure will be executed
// the first element of the returned collection now contains "THIS IS THE VALUE"
$ collection = collect ([ ' this is a value ' ])
-> if (
fn ( Collection $ collection ) => $ collection -> contains ( ' this is a value ' ),
then: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => strtoupper ( $ item )),
else: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => Str:: kebab ( $ item ))
);
// the `else` closure will be executed
// the first element of the returned collection now contains "this-is-another-value"
$ collection = collect ([ ' this is another value ' ])
-> if (
fn ( Collection $ collection ) => $ collection -> contains ( ' this is a value ' ),
then: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => strtoupper ( $ item )),
else: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => Str:: kebab ( $ item ))
);ifAnyMengeksekusi callable yang diteruskan jika koleksinya tidak kosong. Seluruh koleksi akan dikembalikan.
collect ()-> ifAny ( function ( Collection $ collection ) { // empty collection so this won't get called
echo ' Hello ' ;
});
collect ([ 1 , 2 , 3 ])-> ifAny ( function ( Collection $ collection ) { // non-empty collection so this will get called
echo ' Hello ' ;
});ifEmptyMengeksekusi callable yang diteruskan jika koleksinya kosong. Seluruh koleksi akan dikembalikan.
collect ()-> ifEmpty ( function ( Collection $ collection ) { // empty collection so this will called
echo ' Hello ' ;
});
collect ([ 1 , 2 , 3 ])-> ifEmpty ( function ( Collection $ collection ) { // non-empty collection so this won't get called
echo ' Hello ' ;
});insertAfterMenyisipkan item setelah kemunculan pertama item tertentu dan mengembalikan instance Koleksi yang diperbarui. Secara opsional, kunci dapat diberikan.
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAfter ( ' zero ' , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAfter ( 0 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]insertAfterKeyMenyisipkan item setelah kunci tertentu dan mengembalikan instance Koleksi yang diperbarui. Secara opsional, kunci untuk item baru dapat diberikan.
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAfterKey ( 0 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAfterKey ( ' zero ' , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]insertAtMenyisipkan item pada indeks tertentu dan mengembalikan instance Koleksi yang diperbarui. Secara opsional, kunci dapat diberikan.
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAt ( 1 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAt ( 1 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]insertBeforeMenyisipkan item sebelum kemunculan pertama item tertentu dan mengembalikan instance Koleksi yang diperbarui. Secara opsional, kunci dapat diberikan.
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertBefore ( ' two ' , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertBefore ( 2 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]insertBeforeKeyMenyisipkan item sebelum kunci tertentu dan mengembalikan contoh Koleksi yang diperbarui. Secara opsional, kunci untuk item baru dapat diberikan.
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertBeforeKey ( 1 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertBeforeKey ( ' two ' , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]none Memeriksa apakah koleksi tidak berisi kemunculan item tertentu, pasangan nilai kunci, atau lolos uji kebenaran. Fungsi ini menerima parameter yang sama dengan metode pengumpulan contains .
collect ([ ' foo ' ])-> none ( ' bar ' ); // returns true
collect ([ ' foo ' ])-> none ( ' foo ' ); // returns false
collect ([[ ' name ' => ' foo ' ]])-> none ( ' name ' , ' bar ' ); // returns true
collect ([[ ' name ' => ' foo ' ]])-> none ( ' name ' , ' foo ' ); // returns false
collect ([ ' name ' => ' foo ' ])-> none ( function ( $ key , $ value ) {
return $ key === ' name ' && $ value === ' bar ' ;
}); // returns truepaginate Buat instance LengthAwarePaginator untuk item dalam koleksi.
collect ( $ posts )-> paginate ( 5 ); Ini memberi halaman pada konten $posts dengan 5 item per halaman. paginate menerima beberapa opsi, buka dokumen Laravel untuk panduan mendalam.
paginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])
path Mengembalikan item dari koleksi dengan data multidimensi menggunakan notasi "titik". Bekerja dengan cara yang sama seperti metode pull Koleksi asli, tetapi tanpa menghapus item dari koleksi.
$ collection = new Collection ([
' foo ' => [
' bar ' => [
' baz ' => ' value ' ,
]
]
]);
$ collection -> path ( ' foo.bar.baz ' ) // 'value'pluckManyMengembalikan koleksi hanya dengan kunci tertentu.
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 , ' c ' => 100 ],
[ ' a ' => 2 , ' b ' => 20 , ' c ' => 200 ],
]);
$ collection -> pluckMany ([ ' a ' , ' b ' ]);
// returns
// collect([
// ['a' => 1, 'b' => 10],
// ['a' => 2, 'b' => 20],
// ]);pluckManyValuesMengembalikan koleksi yang hanya berisi nilai kunci tertentu.
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 , ' c ' => 100 ],
[ ' a ' => 2 , ' b ' => 20 , ' c ' => 200 ],
]);
$ collection -> pluckMany ([ ' a ' , ' b ' ]);
// returns
// collect([
// [1, 10],
// [2, 20],
// ]);pluckToArrayMengembalikan array nilai dari kunci tertentu.
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 ],
[ ' a ' => 2 , ' b ' => 20 ],
[ ' a ' => 3 , ' b ' => 30 ]
]);
$ collection -> pluckToArray ( ' a ' ); // returns [1, 2, 3]prioritizePindahkan elemen ke awal koleksi.
$ collection = collect ([
[ ' id ' => 1 ],
[ ' id ' => 2 ],
[ ' id ' => 3 ],
]);
$ collection
-> prioritize ( function ( array $ item ) {
return $ item [ ' id ' ] === 2 ;
})
-> pluck ( ' id ' )
-> toArray (); // returns [2, 1, 3]recursiveKonversikan array dan turunannya menjadi koleksi menggunakan rekursi.
collect ([
' item ' => [
' children ' => []
]
])-> recursive ();
// subsequent arrays are now collectionsDalam beberapa kasus, Anda mungkin tidak ingin mengubah semua anak menjadi sebuah koleksi. Anda hanya dapat mengonversi hingga kedalaman tertentu dengan memberikan nomor ke metode rekursif.
collect ([
' item ' => [
' children ' => [
' one ' => [ 1 ],
' two ' => [ 2 ]
]
]
])-> recursive ( 1 ); // Collection(['item' => Collection(['children' => ['one' => [1], 'two' => [2]]])])Ini dapat berguna ketika Anda mengetahui bahwa pada kedalaman tertentu hal ini tidak diperlukan atau dapat merusak kode Anda.
collect ([
' item ' => [
' children ' => [
' one ' => [ 1 ],
' two ' => [ 2 ]
]
]
])
-> recursive ( 1 )
-> map ( function ( $ item ) {
return $ item -> map ( function ( $ children ) {
return $ children -> mapInto (Model::class);
});
}); // Collection(['item' => Collection(['children' => ['one' => Model(), 'two' => Model()]])])
// If we do not pass a max depth we will get the error "Argument #1 ($attributes) must be of type array"rotatePutar item dalam koleksi dengan offset tertentu
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ]);
$ rotate = $ collection -> rotate ( 1 );
$ rotate -> toArray ();
// [2, 3, 4, 5, 6, 1]sectionBy Membagi koleksi menjadi beberapa bagian yang dikelompokkan berdasarkan kunci tertentu. Mirip dengan groupBy tetapi mengikuti urutan item dalam koleksi dan menggunakan kembali kunci yang ada.
$ collection = collect ([
[ ' name ' => ' Lesson 1 ' , ' module ' => ' Basics ' ],
[ ' name ' => ' Lesson 2 ' , ' module ' => ' Basics ' ],
[ ' name ' => ' Lesson 3 ' , ' module ' => ' Advanced ' ],
[ ' name ' => ' Lesson 4 ' , ' module ' => ' Advanced ' ],
[ ' name ' => ' Lesson 5 ' , ' module ' => ' Basics ' ],
]);
$ collection -> sectionBy ( ' module ' );
// [
// ['Basics', [
// ['name' => 'Lesson 1', 'module' => 'Basics'],
// ['name' => 'Lesson 2', 'module' => 'Basics'],
// ]],
// ['Advanced', [
// ['name' => 'Lesson 3', 'module' => 'Advanced'],
// ['name' => 'Lesson 4', 'module' => 'Advanced'],
// ]],
// ['Basics', [
// ['name' => 'Lesson 5', 'module' => 'Basics'],
// ]],
// ]; Tanda tangan lengkap: sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)
simplePaginate Buat instance Paginator untuk item dalam koleksi.
collect ( $ posts )-> simplePaginate ( 5 ); Ini memberi halaman pada konten $posts dengan 5 item per halaman. simplePaginate menerima beberapa opsi, kunjungi dokumen Laravel untuk panduan mendalam.
simplePaginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])
Untuk panduan mendalam tentang penomoran halaman, lihat dokumen Laravel.
sliceBefore Potong nilai dari koleksi sebelum panggilan balik yang diberikan benar. Jika parameter opsional $preserveKeys sebagai true diteruskan, kunci asli akan dipertahankan.
collect ([ 20 , 51 , 10 , 50 , 66 ])-> sliceBefore ( function ( $ item ) {
return $ item > 50 ;
}); // return collect([[20],[51, 10, 50], [66])tail Ekstrak ekor dari koleksi. Jadi semuanya kecuali elemen pertama. Ini adalah singkatan dari slice(1)->values() , namun tetap sangat berguna. Jika parameter opsional $preserveKeys sebagai true diteruskan, parameter tersebut akan mempertahankan kunci dan melakukan fallback ke slice(1) .
collect ([ 1 , 2 , 3 ])-> tail (); // return collect([2, 3])toPairsUbah koleksi menjadi array berpasangan.
$ collection = collect ([ ' a ' => ' b ' , ' c ' => ' d ' , ' e ' => ' f ' ])-> toPairs ();
$ collection -> toArray (); // returns ['a', 'b'], ['c', 'd'], ['e', 'f']transposeTujuan dari transpose adalah untuk memutar array multidimensi, mengubah baris menjadi kolom dan kolom menjadi baris.
collect ([
[ ' Jane ' , ' Bob ' , ' Mary ' ],
[ ' [email protected] ' , ' [email protected] ' , ' [email protected] ' ],
[ ' Doctor ' , ' Plumber ' , ' Dentist ' ],
])-> transpose ()-> toArray ();
// [
// ['Jane', '[email protected]', 'Doctor'],
// ['Bob', '[email protected]', 'Plumber'],
// ['Mary', '[email protected]', 'Dentist'],
// ]try Jika salah satu metode antara try dan catch memunculkan pengecualian, maka pengecualian tersebut dapat ditangani di catch .
collect ([ ' a ' , ' b ' , ' c ' , 1 , 2 , 3 ])
-> try ()
-> map ( fn ( $ letter ) => strtoupper ( $ letter ))
-> each ( function () {
throw new Exception ( ' Explosions in the sky ' );
})
-> catch ( function ( Exception $ exception ) {
// handle exception here
})
-> map ( function () {
// further operations can be done, if the exception wasn't rethrow in the `catch`
}); Meskipun metode ini diberi nama try / catch karena familiar dengan PHP, koleksinya sendiri berperilaku lebih seperti transaksi database. Jadi ketika pengecualian dilempar, koleksi asli (sebelum percobaan) dikembalikan.
Anda dapat memperoleh akses ke koleksi dalam catch dengan menambahkan parameter kedua ke handler Anda. Anda juga dapat memanipulasi koleksi dalam catch dengan mengembalikan nilai.
$ collection = collect ([ ' a ' , ' b ' , ' c ' , 1 , 2 , 3 ])
-> try ()
-> map ( function ( $ item ) {
throw new Exception ();
})
-> catch ( function ( Exception $ exception , $ collection ) {
return collect ([ ' d ' , ' e ' , ' f ' ]);
})
-> map ( function ( $ item ) {
return strtoupper ( $ item );
});
// ['D', 'E', 'F']validate Mengembalikan true jika $callback yang diberikan mengembalikan nilai benar untuk setiap item. Jika $callback adalah string atau array, anggap itu sebagai aturan validasi.
collect ([ ' foo ' , ' foo ' ])-> validate ( function ( $ item ) {
return $ item === ' foo ' ;
}); // returns true
collect ([ ' [email protected] ' , ' bla ' ])-> validate ( ' email ' ); // returns false
collect ([ ' [email protected] ' , ' [email protected] ' ])-> validate ( ' email ' ); // returns trueweightedRandom Mengembalikan item acak berdasarkan beratnya. Dalam contoh ini, item dengan a memiliki peluang paling besar untuk dipilih, dan item dengan c paling kecil.
// pass the field name that should be used as a weight
$ randomItem = collect ([
[ ' value ' => ' a ' , ' weight ' => 30 ],
[ ' value ' => ' b ' , ' weight ' => 20 ],
[ ' value ' => ' c ' , ' weight ' => 10 ],
])-> weightedRandom ( ' weight ' );Alternatifnya, Anda dapat memberikan callable untuk mendapatkan bobotnya.
$ randomItem = collect ([
[ ' value ' => ' a ' , ' weight ' => 30 ],
[ ' value ' => ' b ' , ' weight ' => 20 ],
[ ' value ' => ' c ' , ' weight ' => 10 ],
])-> weightedRandom ( function ( array $ item ) {
return $ item [ ' weight ' ];
});withSizeBuat koleksi baru dengan jumlah item yang ditentukan.
Collection:: withSize ( 1 )-> toArray (); // return [1];
Collection:: withSize ( 5 )-> toArray (); // return [1,2,3,4,5]; Silakan lihat CHANGELOG untuk informasi lebih lanjut tentang apa yang berubah baru-baru ini.
$ composer test Silakan lihat KONTRIBUSI untuk rinciannya.
Jika Anda menemukan bug terkait keamanan, silakan kirim email ke [email protected] alih-alih menggunakan pelacak masalah.
Spatie adalah agen desain web yang berbasis di Antwerp, Belgia. Anda akan menemukan ikhtisar semua proyek sumber terbuka kami di situs web kami.
Lisensi MIT (MIT). Silakan lihat File Lisensi untuk informasi lebih lanjut.