Download the PHP package worksolutions/php-collections without Composer

On this page you can find all versions of the php package worksolutions/php-collections. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package php-collections

PHP Collections

Tests Code Coverage Scrutinizer Code Quality Latest Stable Version

A collection library for PHP. It is used for convenient work with common data structures through functional approach. The main data structures are: List, Map, Stack, Queue, Set. Part of the library is a Stream API. It provides a more functional programming approach to iterating and processing elements.

Read this in other languages: Русский

Requirements

Install

Examples

Basic concepts

The library is based on a consistent approach to data processing and transformation. Creation of a kind of transformation pipeline where you can perform certain steps sequentially. Each step is responsible only for its own little piece of work. In this case, the steps can be reused since they are atomic.

Fundamentally, the library consists of several parts, these are:

Data structures

The library is based on the most popular data structures that are self-sufficient for use without any extraneous libraries and classes. All other parts of the library rely on these structures, in particular the Collection interface. All collection data structures contain many elements with which you can perform basic procedures, such as: traversal, transformation, aggregation, etc.

Collection

[↑ Data structures]

Collection - the main base interface for collections. All data structures except for maps (Map) implement this interface, all additional functionality (Factories, Traversal threads) use this interface. To maintain universality in your applications, it is recommended to use the Collection interface, but only if it does not contradict the purpose of using the structure.

Collections are traversable using a loop.

Interface methods

add - Adding an item to a collection

[↑ Collection]

Adds an item to the end of the collection. Returns true on success orfalse on failure.

addAll - Adding multiple items to a collection

[↑ Collection]

Adds multiple items to the end of the collection. Returns true on success orfalse on failure.

merge - Merging collections

[↑ Collection]

The method merges the current collection with the passed one. Returns true on success orfalse on failure.

clear - Removing all elements of the collection

[↑ Collection]

The method removes all elements of the collection.

remove - Removing a collection item

[↑ Collection]

Removing a specific item in the collection. The method returns a sign of deleting an element. If the element did not exist, it will return false.

contains - Checking for the existence of an element in a collection

[↑ Collection]

Checking if a specific item exists in the collection. If the element does not exist, it will return false.

equals - Comparing two collections for equivalence

[↑ Collection]

The method checks that the passed collection is equal to the current one, which means that all the elements of one collection are contained in another collection and the number of elements is equal. In case of inequality of collections, it will return false.

size - Getting the number of items in a collection

[↑ Collection]

The method returns the number of elements in the collection. If the collection is empty - 0.

isEmpty - Checking a collection for emptiness

[↑ Collection]

The method returns an attribute of an empty collection. If there are elements in the collection, it will return false.

toArray - Getting the elements of a collection as an array

[↑ Collection]

An indexed array method consisting of collection elements, the order of the elements depends on the internal representation.

copy - Getting a copy of a collection

[↑ Collection]

The method returns an exact copy of the collection. Collections are mutable. This means that using modification methods modifies the collection; to ensure that the collection is immutable, it is recommended to use the copy method.

stream - Getting a collection traversal stream (Stream)

[↑ Collection]

Method an object that implements the collection traversal interface (Stream). The collection traversal thread is a very powerful tool, and in most cases you have to deal with it during development. [More ...](#Collection streams)

Traversing a collection with a foreach loop

[↑ Collection]

Collections are traversable in a foreach loop. The collection iteration order depends on the internal implementation of a particular class.

List (ListSequence)

[↑ Data structures]

A list is a data structure in which the order of elements is strictly defined. Lists with the same set of items and different ordering are not equal. The ListSequence interface extends the Collection interface.

ListSequence interface extends interfaces:

Classes implement ListSequence interface:

Interface methods

get - Getting an item by ordinal

[↑ List (ListSequence)]

The method returns the item by index. If no element exists at the index, it will return null. The first element of the list has index 0.

set - Replacing a list item

[↑ List (ListSequence)]

The method replaces the element by an index. Returns the value of the element that has been replaced by the current method. If an attempt is made to replace a non-existing element, an OutOfRangeException will be thrown.

indexOf - Getting the ordinal index of an element

[↑ List (ListSequence)]

The method returns the first index of the found element. If there is no value in the list, it will return null.

lastIndexOf - Getting the ordinal index of the last matched item

[↑ List (ListSequence)]

The method returns the last index of the found element. If there is no value in the list, it will return null.

removeAt - Removing an element by index

[↑ List (ListSequence)]

The method removes an element by an index, elements after the deleted index move closer to the beginning by one position. Returns the value of the removed item. If there is no element by the index, it will return null.

Set

[↑ Data structures]

The set contains only unique elements, the order of the elements can be arbitrary. That is, adding an element using the add method does not guarantee its last place among other elements during iteration, and if there is an element with the same value, the latter will not be added to the set.

Uniqueness is determined by the value, and for objects either by the uniqueness of a specific object, or, if the object implements the HashCodeAware interface, by the uniqueness of the result of calling the getHashCode (): string;.

Set interface extends base interfaces:

Classes implement Set interface:

Queue

[↑ Data structures]

A data structure such as a queue is convenient for sequential processing of data in the order of arrival. It has convenient methods for adding and consuming items. The first element that got into the queue is the first and will leave it.

Queue interface extends base interface :

Classes implements Queue interface:

Interface methods

offer - Inserting an item into the queue

[↑ Queue]

The method adds an item to the end of the queue. Returns false if no item has been added, possibly in case of a limited queue.

poll - Getting an item and removing it from the queue

[↑ Queue]

The method returns an element and removes it from the head of the queue. If there are no items in the queue, a RuntimeException will be thrown.

peek - Getting an item without removing it from the queue

[↑ Queue]

The method returns an element. In this case, the queue does not change, the element remains in its place. If there are no items in the queue, a RuntimeException will be thrown.

Stack

[↑ Data structures]

The stack is a data structure, the logic of which is the opposite of the logic of the queue. The first item on the stack will be the first and popped from it.

Stack interface extends base interface :

Classes implement Stack interface:

Interface methods

push - Pushing an item

[↑ Stack]

The method pushs an item to the top of the stack. Returns false if no element was added, possibly in case of restrictions.

pop - Taking the last added item

[↑ Stack]

The method returns the item from the top of the stack. At the top of the stack is the element added before the received one. If there are no elements on the stack, a RuntimeException will be thrown.

peek - Getting the last added item without modifying the stack

[↑ Stack]

The method returns the item at the top of the stack. If there are no elements on the stack, a RuntimeException will be thrown.

Map

[↑ Data structures]

Map interface represents a mapping, or in other words a dictionary, where each element represents a key-value pair. Map keys are unique in value, if they are objects, then uniqueness is achieved either by the uniqueness of the reference to the object, or if the object implements the HashCodeAware interface by the uniqueness of the result of calling the methodgetHashCode (): string;.

Map interface extends base interface:

Classes implement Stack interface:

Interface methods

put - Adding key/value pair

[↑ Map]

The method adds a key / value pair to the structure object. Returns false if no item was added, possibly in case of restrictions. Both the key, and the value can be data of scalar types, arrays and objects.

get - Getting the value of a pair by key

[↑ Map]

The method returns the value of the pair by the key key. If there is no value, it will return null.

keys - Getting a collection of map keys

[↑ Map]

The method returns a collection consisting of all map keys.

values - Getting a collection of map values

[↑ Map]

The method returns a collection consisting of all the values of the map pairs.

remove - Deleting a pair by key

[↑ Map]

The method removes a pair from the map by the key key.

containsKey - Sign of the presence of a key pair

[↑ Map]

The method returns an indication of the presence of a pair with the key key.

containsValue - Sign of the presence of a pair by value

[↑ Map]

The method returns an indication of the presence of a pair with the value value.

size - Number of pairs in the card

[↑ Map]

The method returns the number of pairs.

stream - Getting traverse stream with collection of pair key/value (Stream)

[↑ Map]

Method returns object of Stream interface. Internal collection elements are pair of key/value.

Traverse map in foreach loop

[↑ Map]

Object of Map interface can iterated in foreach loop. In this case keys and values will be passed before ones. Key can be of any type except an array.

Collection factory

[↑ Up]

The CollectionFactory factory allows you to create collection objects without using an implementation-specific constructor, or also has other convenient methods for creating collection objects. At the moment, the main structure of the library is ArrayList, which is generated by the factory in static methods.

Example

Collection creation factory methods

CollectionFactory::from - Generating a collection from an array of elements

[↑ Collection factory]

The method creates a collection whose elements consist of the elements of the passed array.

At the moment, the implementation of the collection is ArrayList, in the future the specific implementation may change, when calling this method, you should rely only on the Collection interface.

CollectionFactory::fromIterable - Generating a collection using any iterable

[↑ Collection factory]

The method creates a collection whose elements consist of the elements of the passed iterator.

At the moment, the implementation of the collection is ArrayList, in the future the specific implementation may change, when calling this method, you should rely only on the Collection interface.

_CollectionFactory::numbers - Generating a collection of a sequence of integers

[↑ Collection factory]

The method creates a collection whose elements consist of a sequence of integers [$ from .. $ to]. If the $ to parameter is not passed, the[0 .. $ from]collection will be returned.

At the moment, the implementation of the collection is ArrayList, in the future the specific implementation may change, when calling this method, you should rely only on theCollection interface.

CollectionFactory::generate - Generating a collection using a generator

[↑ Collection factory]

The method creates a collection of size $ times, whose elements consist of the values of the results of calling the generator$ generator.

At the moment, the implementation of the collection is ArrayList, in the future the specific implementation may change, when calling this method, you should rely only on theCollection interface. If you need a specific type of a collection instance, you need to use implementation constructors or their static methods.

MapFactory::fromIterable - Map generating from any iterated value

[↑ Collection factory]

Method created map object from any iterated object.

MapFactory::assoc - Map generating from associative array

[↑ Collection factory]

Method creates map object from associative array.

Collection streams

[↑ Up]

For more convenient traversal and conversion of collections, you must use Streams. Basically all computation should be done via stream. To get a stream, you need to call the collection method Collection::stream ().

Processing a collection with stream occurs through the execution of functions, the interfaces of which must match the traversal / transformation purpose. There are six of them:

All streams belong to the Stream interface, which means that the description of the interface guarantees its correct execution regardless of the specific implementation, exceptions are only special cases of stream behavior (when).

Stream`s guarantee that after each modification method the getCollection method will return different object instances, which is a safe way from a security point of view to maintain immutability during conversion.

Stream interface methods

each - Traversing collection items

[↑ Streams]

The method applies the $ consumer function to each element of the stream collection. The result of the function is not considered. Calling the each method does not change the collection of the stream, but at the same time accesses every item in the collection.

walk - A limited traversal of collection items

[↑ Streams]

The method applies the $consumer function to each element of the stream collection, just as it does in the each method. The result of the function is not considered. Calling the each method does not change the collection of the stream, but at the same time accesses every item in the collection.

filter - Filtering collection items

[↑ Streams]

The method applies the $ predicate function to each element of the stream collection. If the call to the predicate from the elements returns a negative result - false, 0, ', [], the element is excluded from the collection.

map - Converting stream collection items

[↑ Streams]

The method applies a stream to each element of the collection, replaces the passed elements of the collection with the results of the function execution.

reorganize - Stream collection conversion

[↑ Streams]

The method applies $reorganizer to the inner collection, then replaces the inner collection with the result of the method call. Needed when conversions should be performed based on data from a complete collection.

collect - Collecting data

[↑ Streams]

The method applies $collector to the internal collection and returns the result. It is necessary when you need to perform the final action on the collection using a stream. Terminal method.

sort - Sorting items in a collection

[↑ Streams]

The method sorts the items according to the work of the $comparator. The comparator determines the sort order of the two values. Must return an integer less than, equal to, or greater than zero if the first argument is respectively less than, equal to, or greater than the second. php.net usort

sortDesc - Sorting elements of a collection in reverse order

[↑ Streams]

The method sorts the elements according to the work of the $ comparator, but unlike the usual sort function, the elements will be arranged in descending order. The compiler determines the sort order of the two values. Must return an integer less than, equal to, or greater than zero if the first argument is respectively less than, equal to, or greater than the second. php.net usort

sortBy Sorting collection items by value

[↑ Streams]

The method sorts the elements according to the received value of the $ extractor function for each element. The function must return a scalar value to enable independent optimized sorting. The method of sorting by value in reverse order sortByDesc works similarly.

reduce - Reducing a collection into a single value

[↑ Streams]

The method converts the collection to a single value. The function is passed the values $el of the iterable element and the result of calling the same function on the previous element$carry. In the first iteration, $carry === null. Terminal method.

when - Constraining stream modification by condition

[↑ Streams]

The method restricts modification if $condition is not met and all modification and bypass methods will not be called. The opposite method is [always](#Removing stream modification constrains).

Locked methods:

always - Removing stream modification constrains

[↑ Streams]

If the stream was previously blocked for modifications via the [when condition](#Constraining stream modification by condition), thealways method cancels the restrictions on further calls of modifying methods.

getCollection - Getting a stream collection

[↑ Streams]

The method returns the collection based on the previously performed conversions. Even if conversion methods are still called on the stream, the resulting collection will remain unchanged. Terminal method.

allMatch - Full match of all elements by predicate

[↑ Streams]

The method will return true if all calls to$predicate on the elements of the collection are true (true). Terminal method.

anyMatch- Partial match of all elements by predicate

[↑ Streams]

The method will return true if at least one call to$ predicate over the elements of the collection is true (true). Terminal method.

findAny - Getting an arbitrary collection item

[↑ Streams]

The method returns an arbitrary element of the collection, or null if the collection is empty. Does not guarantee that the item is randomly selected. Terminal method.

findFirst- Getting the first item in a collection

[↑ Streams]

The method will return the first element of the collection, or null if the collection is empty. Terminal method.

findLast- Getting the last item in a collection

[↑ Streams]

The method will return the last element of the collection, or null if the collection is empty. Terminal method.

min - Getting the minimum element of a collection

[↑ Streams]

The method will return the smallest item in the collection as compared by the comparator function, or null if the collection is empty. Terminal method.

max - Getting the maximum item in a collection

[↑ Streams]

The method will return the largest item in the collection as compared by the comparator function, or null if the collection is empty. Terminal method.

reverse - Reverse the elements of the collection

[↑ Streams]

Method converts the order of the elements to the reversed sequence.

limit - Shrink the collection to the specified size

[↑ Streams]

The method reduces the number of elements to the specified size. If the number of elements is already less than specified in the $size limit, the number of elements will remain the same.

Traversal and transformation functions

[↑ Up]

The library contains constructors of the most popular functions that initiate functions to work through traversal and transformation threads with pre-prepared parameters.

For example:

Calling the constructor of the function Predicates::equal(10) will return a function for comparing the input parameter with the value 10.

The functions used in the library are divided into the following types:

Each function type must have a corresponding interface for use in specific stream methods.

Predicates

[↑ Traversal and transformation functions] A group of function constructors that are used to filter the stream collection. All methods return initialized functions with the interface: <Fn($el: mixed): bool>. Predicates also let you work with object properties. For example, a property of an object myProperty means the presence of a public property in the object called myProperty or the presence of a getter method -getMyProperty.

lock – Locking

[↑ Predicates]

The method initiates a function that, for any set of input data, will return false. In essence, the method spawns a stream blocking function.

notResistance – Passing all values

[↑ Predicates]

The method initiates a function that, for any set of input data, will return true.

notNull – Checking values for emptiness

[↑ Predicates]

The method initiates a function that, for any set of input data, will return true.

eachEven - Passing even call items

[↑ Predicates]

The method initiates a function that, every even call, will return true and, accordingly, in other cases -false.

nth – Passing specified elements

[↑ Predicates]

The method initiates a function that every $number call - will returntrue and, accordingly, in other cases - false.

equal – Equivalence check

[↑ Predicates]

The method initiates a function that returns true when the collection item matches the value of $value.

lockDuplicated – Locking duplicate values

[↑ Predicates]

The method initiates a function that returns true only for calls with unique members.

lessThan – Checking a value for the "less" condition

[↑ Predicates]

The method initiates a function for comparing elements with the value $value.

lessOrEqual – Checking a value for a "less than or equal" condition

[↑ Predicates]

The method initiates a function for comparing elements with the value $value.

greaterThan – Checking a value for the "greater than" condition

[↑ Predicates]

The method initiates a function for comparing elements with the value $value.

greaterOrEqual – Checking a value for a "greater than or equal" condition

[↑ Predicates]

The method initiates a function for comparing elements with the value $value.

not – Checking a value for inequality

[↑ Predicates]

The method initiates a function for checking the inequality of collection elements with the value $value.

in – Checking a value for being in group of values

[↑ Predicates]

The method initiates a function to check if elements are in an array $values.

notIn – Checking a value for absence in group of values

[↑ Predicates]

The method initiates a function for checking the absence of elements in the set $values.

where – Checking object property for equivalence

[↑ Predicates]

The method initiates the function of checking the property of the element object for equality to the value of $value.

whereNot – Checking object properties for inequality

[↑ Predicates]

The method initiates the function of checking the property of the element object for inequality with the value of $value.

whereIn – Checking a property of an object for being in group of values

[↑ Predicates]

The method initiates a function for checking whether the value of an object property is in the set $values.

whereNotIn – Checking an object property for absence in group of values

[↑ Predicates]

The method initiates a function for checking the absence of an object property value in the set $values.

whereGreaterThan – Checking an object property for the "greater than" condition

[↑ Predicates]

The method initiates a function for comparing the value of an object's property with $value.

whereLessThan – Checking an object property for the "less" condition

[↑ Predicates]

The method initiates a function for comparing the value of an object's property with $value.

whereGreaterOrEqual – Checking an object property for a "greater than or equal" condition

[↑ Predicates]

The method initiates a function for comparing the value of an object's property with $value.

whereLessOrEqual – Checking an object property for a "less than or equal" condition

[↑ Predicates]

The method initiates a function for comparing the value of an object's property with $value.

Comparators

[↑ Traversal and transformation functions]

Comparison function constructors group. Comparison functions are needed when using sorting methods to arrange the elements in the correct order. The resulting sort functions have an interface <Fn($a: mixed, $b: mixed): int>, with the same logic as [https://www.php.net/manual/ru/function.usort].

scalarComparator Comparison of scalar values

[↑ Comparators]

The method initiates a function that compares two values. The comparison function returns an integer less than, equal to, or greater than zero if the first argument is respectively less than, equal to, or greater than the second.

objectPropertyComparator – Comparing object properties

[↑ Comparators]

The method initiates a function that compares two property values of objects. The comparison function returns an integer less than, equal to, or greater than zero if the first argument is respectively less than, equal to, or greater than the second.

callbackComparator – Defining a function to compare values

[↑ Comparators]

The method initiates a function that compares the two values based on their processing by the $fun function. The comparison function returns an integer less than, equal to, or greater than zero if the first argument is respectively less than, equal to, or greater than the second.

Converters

[↑ Traversal and transformation functions]

A group of constructors of functions for converting elements. The result of the converter function is <Fn($obj: mixed): mixed>.

toPropertyValue Convert each item in the collection to a property value

[↑ Converters]

The method creates a function that returns the value of an object property.

toProperties Converting each item in a collection to an associative array

[↑ Converters]

The method initiates a function that returns an associative array of object properties, whose keys are property names.

Reorganizers

[↑ Traversal and transformation functions]

Stream conversion method constructors. Unlike element transformation functions, where each element of the original collection corresponds to an element of the new collection given the position of the first, stream transformation methods create a derived new collection with an arbitrary number of elements.

shuffle - Changing the order of a collection item

[↑ Reorganizers]

The method initiates a function that returns a new collection with reordered items. Items will follow in random order.

random - Getting random elements of a collection

[↑ Reorganizers]

random($count = 1: int): Closure; \\ <Fn(): Collection>

The method initiates a function, the function returns a new collection that contains a random bounded set of elements in the original collection.

chunk - Splitting into multiple collections of a specified size

[↑ Reorganizers]

chunk($size: int): Closure; \\ <Fn(): Collection>

The method initiates a function, the function returns a collection of collections whose number of elements is less than or equal to $size.

collapse - Getting a collection without additional nesting levels

[↑ Reorganizers]

collapse(): Closure; \\ <Fn(): Collection>

The method initiates a function, the function returns a collection without nested containers. In this context, containers are iterable data structures.

Consumers

[↑ Traversal and transformation functions]

Consumer function constructors. Contains one function for printing element values. Basically, each consumer function is developed individually in the project source code.

dump - Listing the values of collection items

[↑ Consumers]

dump(): Closure; \\ <Fn(): Collection>

The method initiates a function that prints the passed value to the output stream.

Aggregation

[↑ Traversal and transformation functions]

by

[↑ Aggregation]

$group = Group::by($fieldName): Group;

addToSet

[↑ Aggregation]

Group::addToSet($sourceKey, $destKey): Group;

avg

[↑ Aggregation]

Group::avg($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 50],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->avg('price', 'avg');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['avg' => 40],
    'transport' => ['avg' => 75],
    'entertainment' => ['avg' => 30],
];
*/

count

[↑ Aggregation]

Group::count($destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'tea', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->count('total');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['total' => 3],
    'transport' => ['total' => 1],
    'entertainment' => ['total' => 2],
];
*/

first

[↑ Aggregation]

Group::first($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->first('name', 'item');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['item' => 'potato'],
    'transport' => ['item' => 'taxi'],
    'entertainment' => ['item' => 'Knicks game'],
];
*/

last

[↑ Aggregation]

Group::last($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->last('name', 'item');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['item' => 'milk'],
    'transport' => ['item' => 'airplane'],
    'entertainment' => ['item' => 'cinema'],
];
*/

max

[↑ Aggregation]

Group::max($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->max('price', 'max');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['max' => 50],
    'transport' => ['max' => 100],
    'entertainment' => ['max' => 300],
];
*/

min

[↑ Aggregation]

Group::min($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->min('price', 'min');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['min' => 30],
    'transport' => ['min' => 50],
    'entertainment' => ['min' => 30],
];
*/

sum

[↑ Aggregation]

Group::sum($sourceKey, $destKey): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->sum('price', 'spent');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['spent' => 80],
    'transport' => ['spent' => 150],
    'entertainment' => ['spent' => 330],
];
*/

addAggregator

[↑ Aggregation]

Group::addAggregator($destKey, $callbackFn): Group;

use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;
use \WS\Utils\Collections\Collection;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->addAggregator('names', function (Collection $collection) { 
    $result = [];
    foreach ($collection as $item) {
        $result[] = $item['name'];
    }
    return implode(', ', $result);
});
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['names' => 'potato, milk'],
    'transport' => ['names' => 'taxi, airplane'],
    'entertainment' => ['names' => 'Knicks game, cinema'],
];
*/

All aggregators can be combined with each other to get the desired result


use \WS\Utils\Collections\CollectionFactory;
use \WS\Utils\Collections\Functions\Group\Group;

$items = [
    ['name' => 'potato', 'type' => 'groceries', 'price' => 30],
    ['name' => 'milk', 'type' => 'groceries', 'price' => 50],
    ['name' => 'taxi', 'type' => 'transport', 'price' => 100],
    ['name' => 'airplane', 'type' => 'transport', 'price' => 50],
    ['name' => 'Knicks game', 'type' => 'entertainment', 'price' => 300],
    ['name' => 'cinema', 'type' => 'entertainment', 'price' => 30],
];

$aggregation = Group::by('type')->avg('price', 'avg')->min('price', 'min')->max('price', 'max');
$result = CollectionFactory::from($items)
    ->stream()
    ->collect($aggregation)
;
/* Result ->
[
    'groceries' => ['avg' => 40, 'min' => 30, 'max' => 50],
    'transport' => ['avg' => 75, 'min' => 50, 'max' => 100],
    'entertainment' => ['avg' => 165, 'min' => 30, 'max' => 300],
];
*/

All versions of php-collections with dependencies

PHP Build Version
Package Version
Requires php Version ^7.3 || ~8.0
ext-json Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package worksolutions/php-collections contains the following files

Loading the files please wait ....