侧边栏壁纸
  • 累计撰写 168 篇文章
  • 累计创建 71 个标签
  • 累计收到 35 条评论

目 录CONTENT

文章目录

Laravel Collection集合使用filter方法

神兵小将
2023-02-08 / 0 评论 / 20 点赞 / 516 阅读 / 1,052 字 / 正在检测是否收录...

代码示例 #1

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $students = collect([
            ["id" => 1, "name" => "Sanjay", "email" => "sanjay@gmail.com", "marks" => 88],
            ["id" => 2, "name" => "Vijay", "email" => "vijay@gmail.com", "marks" => 70],
            ["id" => 3, "name" => "Ashish", "email" => "ashish@gmail.com", "marks" => 75]
        ]);

        $passed = $students->filter(function ($value, $key) {
            return data_get($value, 'marks') > 70;
        });

        $passed = $passed->all();

        dd($passed);
    }
}

概念

$passed = $students->filter(function ($value, $key) {
      return data_get($value, 'marks') > 70;
});

输出
image-1675861275010

代码示例 #2

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $data = collect([2, 3, 5, null, false, '', 0, []]);

        $data = $data->filter()->all();

        dd($data);
    }
}

在这种情况下,它将从数组中删除假值

image-1675861288029

20

评论区