Collection in Laravel是一個API包裝器,它可以幫助您處理在陣列上執行的不同操作。它使用Illuminate\Support\Collection類別來處理Laravel中的陣列。
要從給定的陣列建立一個集合,您需要使用collect()輔助方法,它會傳回一個集合實例。之後,您可以在集合實例上使用一系列方法,例如轉換為小寫,對集合進行排序。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Collection; class UserController extends Controller{ public function index() { $mynames = collect(['Andria', 'Josh', 'James', 'Miya', 'Henry']); print_r($mynames); } }
當您在瀏覽器中測試相同內容時,您將獲得以下輸出−
#Illuminate\Support\Collection Object( [items:protected] => Array( [0] => Andria [1] => Josh [2] => James [3] => Miya [4] => Henry ) [escapeWhenCastingToString:protected] => )
要新增值,您可以使用集合上的 push() 或 put() 方法。
使用push()方法。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Collection; class UserController extends Controller{ public function index() { $mynames = collect(['Andria', 'Josh', 'James', 'Miya', 'Henry']); $mynames->push('Heena'); print_r($mynames); } }
上述程式碼的輸出是 -
Illuminate\Support\Collection Object( [items:protected] => Array( [0] => Andria [1] => Josh [2] => James [3] => Miya [4] => Henry [5] => Heena ) [escapeWhenCastingToString:protected] => )
使用put()方法
#當您有一個帶有鍵:值對的集合時,使用put()方法
['firstname' => 'Siya', 'lastname' => 'Khan', 'address'=>'xyz']
讓我們利用put()方法將一個鍵值對加入上述集合。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Collection; class UserController extends Controller{ public function index() { $stdDetails = collect(['firstname' => 'Siya', 'lastname' => 'Khan', 'address'=>'xyz']); $stdDetails->put('age','30'); print_r($stdDetails); } }
上述程式碼的輸出是 -
Illuminate\Support\Collection Object( [items:protected] => Array( [firstname] => Siya [lastname] => Khan [address] => xyz [age] => 30 ) [escapeWhenCastingToString:protected] => )
使用帶有陣列值的集合推送。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Collection; class UserController extends Controller{ public function index() { $myNames = collect([ ['userid'=>1, 'name'=>'Andria'], ['userid'=>2, 'name'=>'Josh'], ['userid'=>3, 'name'=>'James'] ]); $myNames->push(['userid'=>4, 'name'=>'Miya']); print_r($myNames); } }
上述程式碼的輸出是 -
Illuminate\Support\Collection Object( [items:protected] => Array( [0] => Array( [userid] => 1 [name] => Andria ) [1] => Array( [userid] => 2 [name] => Josh ) [2] => Array( [userid] => 3 [name] => James ) [3] => Array( [userid] => 4 [name] => Miya ) ) [escapeWhenCastingToString:protected] => )
以上是如何在Laravel中為集合新增值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!