您好,欢迎访问一九零五行业门户网

如何在Laravel中向集合添加新值?

collection in laravel是一个api包装器,它帮助您处理在数组上执行的不同操作。它使用illuminate\support\collection类来处理laravel中的数组。
要从给定的数组创建一个集合,您需要使用collect()辅助方法,它返回一个集合实例。之后,您可以在集合实例上使用一系列方法,如转换为小写,对集合进行排序。
example 1 的中文翻译为:示例1<?phpnamespace 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() 方法。
示例 2使用push()方法。
<?phpnamespace 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] =>)
示例 3使用put()方法
当您有一个带有键:值对的集合时,使用put()方法
['firstname' => 'siya', 'lastname' => 'khan', 'address'=>'xyz']
让我们利用put()方法将一个键值对添加到上述集合中。
<?phpnamespace 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] =>)
example 4 的中文翻译为:示例4使用带有数组值的集合推送。
<?phpnamespace 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中向集合添加新值?的详细内容。
其它类似信息

推荐信息