originphp/collection

OriginPHP Collection

2.0.1 2021-01-04 11:09 UTC

This package is auto-updated.

Last update: 2024-09-04 19:02:44 UTC


README

license build coverage

您可以使用数组或一个实例为可遍历的对象来创建一个Collection

安装

要安装此包

$ composer require originphp/collection

创建一个集合

要创建一个集合

use Origin\Collection\Collection;
$collection = new Collection($array);

还有一个辅助函数可供您使用。

$collection = collection($array);

集合

在您完成数据处理后,可以使用toArraytoList将集合转换为。一些方法返回布尔值(例如every)或数字(例如中位数、平均值等),然而大多数将返回一个新的集合,然后可以通过其他方法进行链式调用。

迭代方法

提取

从一个集合中提取单列以创建一个列表。您可以使用点表示法。

    $collection = collection($books);
    $authors = $collection->extract('authors.name');
    $list = $authors->toList();

您还可以使用回调函数

    $collection = collection($books);
    $books = $collection->extract(function ($book) {
      return $book->name . ' written by ' . $book->author->name;
    });
    $list = $books->toList();

每个

遍历集合中的每个项目。请注意,每个不会修改数据。如果要修改数据,则使用map

    $collection = new Collection($books);
    $collection->each(function ($value, $key) {
        echo "{$key} - {$value}";
    });

映射

这将遍历集合中的每个项目,并通过回调函数传递值,该回调函数可以修改数据并返回它,从而在过程中创建一个新的集合。

    $collection = new Collection([
        'a'=>1,'b'=>2,'c'=>3
        ]);

    // using a callable must return a value
    $plusOneCollection = $collection->map(function ($value, $key) {
        return $value + 1;
    });

组合

使用键和值创建一个新的集合。

    $collection = new Collection($results);
    $combined = $collection->combine('id', 'name'); 
    $array = $combined->toArray(); //[1=>'Tom','2'=>'James']

组合的结果也可以按第三个键分组。

    $collection = new Collection($results);
    $result => $collection->combine('id', 'name','profile'); 
    $array = $result->toArray(); // ['admin' => [1=>'tom',2=>'tim']]

分块

将集合分成多个部分

  $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
  $chunks = $collection->chunk(5);
  $array = $chunks->toArray();  // [[1,2,3,4,5],[6,7,8,9,10],[11,12]];

过滤方法

过滤

使用回调函数过滤结果

    $collection = new Collection($books);
    $inStock = $collection->filter(function ($book) {
        return $book->in_stock ===  true;
    });

拒绝

这是过滤的反面。

    $collection = new Collection($books);
    $notInStock = $collection->reject(function ($book) {
        return $book->in_stock ===  true;
    });

每个

对集合中的每个项目运行真值测试。

    $collection = new Collection($books);
    $allBooksInStock = $collection->every(function ($book) {
        return $book->in_stock > 0;
    });
    if($allBooksInStock){
        ...
    }

一些

检查是否至少有一个项目匹配过滤器

    $collection = new Collection($books);
    $anyThingInStock = $collection->some(function ($book) {
        return $book->in_stock > 0;
    });
    if($anyThingInStock){
        ...
    }

排序

sortBy

按字段或回调对集合进行排序。要按字段排序,您可以使用点表示法。

    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy('authors.name');

按回调排序。

    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy(function ($book) {
        return $book->author->name . '-' . $book->name;
    });

sortBy方法接受3个参数,第一个参数是路径或回调。

第二个参数是方向,可以是SORT_DESCSORT_ASC

第三个参数取决于数据和与PHP Sort相同,包括

  • SORT_NUMERIC - 用于数字
  • SORT_STRING - 用于字符串
  • SORT_NATURAL - 用于自然排序

聚合

最小值

获取具有最小值的第一个项。

    $collection = new Collection($authors);
    $author = $collection->min('rating');

按回调排序。

    $collection = new Collection($books);
    $author = $collection->min(function ($book) {
        return $book->author->score;
    });

最大值

获取具有最小值的第一个项。

    $collection = new Collection($books);
    $author = $collection->max('authors.rating');

按回调排序。

    $collection = new Collection($books);
    $author = $collection->max(function ($book) {
        return $book->author->score;
    });

计数

求和

从字段或回调获取总和。

    $collection = new Collection($books);
    $inStock = $collection->sumOf('in_stock');

使用回调获取总和

    $collection = new Collection($books);
    $points = $collection->sumOf(function ($book) {
        return $book->author->rating;
    });

平均

从字段或回调获取平均值。

    $collection = new Collection($books);
    $avgRating = $collection->avg('authors.rating');

使用回调获取平均值

    $collection = new Collection($books);
    $avgRating = $collection->avg(function ($book) {
        return $book->author->rating;
    });

中位数

从字段或回调获取中位数。

    $collection = new Collection($books);
    $median = $collection->median('authors.rating');

使用回调获取中位数

    $collection = new Collection($books);
    $median = $collection->median(function ($book) {
        return $book->author->rating;
    });

计数

这是一个用于计数集合中项的函数,当与其他集合方法(如take或chunk)一起使用时非常有用。

    $collection = new Collection($books);
    $count = $collection->count();

按字段计数

按字段和值计数,并按组显示结果。

    $collection = new Collection($books);
    $counts = $collection->countBy('authors.type'); // ['famous'=>10,'new'=>20]

您还可以使用回调。

    // ['odd'=>2,'even'=>3]
    $collection = new Collection($books);
    $counts = $collection->countBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    }); 

分组

groupBy

按字段或回调分组结果。

    $collection = new Collection($books);
    $grouped = $collection->groupBy('authors.type');
    $array = $grouped->toArray();

您还可以使用回调。

    $collection = new Collection($books);
    $grouped = $collection->groupBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    });
    $array = $grouped->toArray();

插入数据

插入

将值插入到集合中每个项目的路径。

    $collection = new Collection($books);
    $newCollection = $collection->insert('authors.registered',true);
    $books = $newCollection->toArray();

使用相同的示例,我将使用辅助函数链式调用它。这可以与任何返回新集合的方法一起完成。

    $books = collection($books)->insert('authors.registered',true)->toArray();

其他

从一个集合中取出多个项目。

    $collection = new Collection($books);
    $firstLot = $collection->take(10);
    $secondLot = $collection->take(10,11);