使用 contains() 方法
我们将看到如何在集合中使用 contains()。
假设我们有 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->contains('Nepal'); /* true */
$collection->contains('China'); /* false */
}
}
概念
$collection->contains('Nepal'); /* true */
代码示例 #2
Laravel 集合包含与键值检查
<?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->contains('name', 'Vijay'); /* true */
$collection->contains('name', 'Dhananjay'); /* false */
}
}
概念
$collection->contains('name', 'Vijay'); /* true */
代码示例 #3
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class SiteController extends Controller
{
public function index()
{
Product::create(['name' => 'Science Books', 'price' => 2200]);
Product::create(['name' => 'Tshirts', 'price' => 1250]);
Product::create(['name' => 'Jeans', 'price' => 1500]);
Product::get()->contains('name', 'Jeans'); /* true */
Product::get()->contains('name', 'Electronic Device'); /* false */
Product::get()->contains('price', 1500); /* true */
}
}
概念
Product::get()->contains('name', 'Jeans'); /* true */
代码示例 #4
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class SiteController extends Controller
{
public function index()
{
Product::create(['name' => 'Science Books', 'price' => 2200]);
Product::create(['name' => 'Tshirts', 'price' => 1250]);
Product::create(['name' => 'Jeans', 'price' => 1500]);
Product::get()->contains(function ($key, $value) {
return $value->price > 1000;
}); // true
}
}
概念
Product::get()->contains(function ($key, $value) {
return $value->price > 1000;
}); // true
使用 containsStrict() 方法
我们将看到如何在集合中使用 containsStrict()。它还检查值和类型。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$collection = collect([100, 150, 200, 250, 300]);
$collection->containsStrict('150'); /* false */
$collection->containsStrict(150); /* true */
}
}
评论区