使用 push方法
我们将看到如何在集合中使用 push方法。
假设我们有 SiteController.php
在/app/Http/Controllers
文件夹中的控制器文件。
代码示例 #1
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$collection = collect([
"India",
"Australia",
"South Africa",
"Nepal"
]);
$collection->push("New Zealand");
$collection->all();
dd($collection);
}
}
概念
$collection->push("New Zealand");
输出
代码示例 #2
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$collection = collect([
["id" => 1, "name" => "Sanjay", "email" => "sanjay@gmail.com"],
["id" => 2, "name" => "Vijay", "email" => "vijay@gmail.com"],
["id" => 3, "name" => "Ashish", "email" => "ashish@gmail.com"]
]);
$collection->push(['id' => 4, 'name' => 'Dhananjay Negi', 'email' => 'dj@gmail.com']);
$collection->all();
dd($collection);
}
}
概念
$collection->push(['id' => 4, 'name' => 'Dhananjay Negi', 'email' => 'dj@gmail.com']);
输出
使用 put方法
我们将看到如何在集合中使用 put。它用于向集合数据添加新的键值对。
假设我们有 SiteController.php
在/app/Http/Controllers
文件夹中的控制器文件。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$collection = collect([
"id" => 1,
"name" => "Sanjay",
"email" => "sanjay@gmail.com"
]);
$collection->put('designation', 'Web Developer');
$collection->all();
dd($collection);
}
}
概念
$collection->put('designation', 'Web Developer');
输出
评论区