牛牛在线工具

Collection::find()

收录 8868 个 PHP 函数,含用途说明与用法示例。

Collection::find()

在集合中查找满足指定条件的元素,并返回一个新的集合

函数名:Collection::find() 适用版本:PHP 5.3+ 函数用法:Collection::find()函数用于在集合中查找满足指定条件的元素,并返回一个新的集合。 语法: Collection Collection::find ( callable $callback ) 参数: $callback:一个回调函数,用于定义要查询的条件。函数应该接收一个集合元素作为参数,并返回一个布尔值,表示该元素是否满足条件。 返回值:一个新的集合,包含满足条件的元素。 示例: 假设我们有一个学生集合,每个学生都有一个成绩属性。我们想要找出成绩大于等于80的学生。 class Student { public $name; public $score; public function __construct($name, $score) { $this->name = $name; $this->score = $score; } } $students = new Collection([ new Student('Alice', 75), new Student('Bob', 90), new Student('Charlie', 82), new Student('David', 65) ]); $passedStudents = $students->find(function($student) { return $student->score >= 80; }); print_r($passedStudents); 输出: Collection Object ( [items:protected] => Array ( [1] => Student Object ( [name] => Bob [score] => 90 ) [2] => Student Object ( [name] => Charlie [score] => 82 ) ) ) 在上面的示例中,我们使用Collection::find()函数查找满足成绩大于等于80的学生。返回的集合$passedStudents包含了Bob和Charlie这两个学生对象。