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.
Download worksolutions/php-collections
More information about worksolutions/php-collections
Files in worksolutions/php-collections
Package php-collections
Short Description Collections library for php language
License MIT
Informations about the package php-collections
PHP Collections
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. Each structure has its own peculiarity, expressed through the interface and descriptions to it, and implementation. In this case, the implementation of the behavior of data structures can be different.
- Collection factory. The collection factory has many static methods for conveniently creating collections.
- Collection streams. Streams traverse and transform collections, with each transformation creating a new instance of the collection.
- Traversal and transformation functions. The function set consists of pre-prepared function constructors for easy use during the traversal. By their example, you can create and use your own functions that are more specific to your subject area.
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
- List (ListSequence)
- Set
- Queue
- Stack
- Map
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
- addAll – Adding multiple items to a collection
- merge – Merging collections
- clear – Removing all elements of the collection
- remove – Removing a collection item
- contains – Checking for the existence of an element in a collection
- equals – Comparing two collections for equivalence
- size – Getting the number of items in a collection
- isEmpty – Checking a collection for emptiness
- toArray – Getting the elements of a collection as an array
- copy – Getting a copy of a collection
- stream – Getting a collection traversal stream (Stream)
- Traversing a collection with a foreach loop
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
- set – Replacing a list item
- indexOf – Getting the ordinal index of an element
- lastIndexOf – Getting the ordinal index of the last matched item
- removeAt – Removing an element by index
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
- poll – Getting an item and removing it from the queue
- peek – Getting an item without removing it from the queue
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
- pop – Taking the last added item
- peek – Getting the last added item without modifying the stack
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
- get – Getting the value of a pair by key
- keys – Getting a collection of map keys
- values – Getting a collection of map values
- remove – Deleting a pair by key
- containsKey – Sign of the presence of a key pair
- containsValue – Sign of the presence of a pair by value
- size – Number of pairs in the card
- stream - Getting traverse stream with collection of key/value pair (Stream)
- Traverse map in foreach loop
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
- CollectionFactory::fromIterable – Generating a collection using any iterable
- CollectionFactory::numbers – Generating a collection of a sequence of integers
- CollectionFactory::generate – Generating a collection using a generator
- MapFactory::fromIterable – Map generation from any iterated value
- MapFactory::assoc – Map generation from associative array
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:
- Predicate. Used to filter elements
filter
, the element remains in the stream collection in case the predicate called for this element returns a boolean positive value. The library already contains some prepared predicates. - Converter. Functions of this type are used to transform the
map
stream collection. The converter must return a value that, by some attribute, corresponds to the passed element of the collection. The library already contains some prepared converters. - Consumer. Consumer functions do not modify the stream collection, but are used to traverse the
each
collection. The passed function will be called for each element of the collection; the result of the function is not taken into account. The library already contains some prepared consumers. - Comparator. Comparators participate in sorting items to determine the sort order of 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. The library already contains some prepared comparison functions.
- Reorganizer. Conversion functions convert one collection to another
reorganize
without changing the stream object. Transformations are necessary when you need to get the final collection not just by transforming one element to another, but to form a new collection based on all the information in the original collection. Examples are methods for shuffling shuffle elements or forming chunks. The library already contains some prepared reorganizers. - Collector. Data collection functions are applied to a stream using the collect method, in fact, the result of executing the functions of this group will be the result of executing the stream. The collect method is terminal, that is, calling this method terminates the stream.
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
- walk – Limited traversal of collection items
- filter – Filtering collection items
- map – Converting stream collection items
- reorganize – Stream collection conversion
- collect – Collecting data
- sort – Sorting items in a collection
- sortBy – Sorting collection items by value
- sortDesc – Sorting elements of a collection in reverse order
- sortByDesc – Sorting elements of a collection by value in reverse order
- reduce – Reducing a collection into a single value
- when – Constraining stream modification by condition
- always – Removing stream modification constrains
- getCollection – Getting a stream collection
- allMatch – Full match of all elements by predicate
- anyMatch – Partial match of all elements by predicate
- findAny – Getting an arbitrary collection item
- findFirst – Getting the first item in a collection
- findLast – Getting the last item in a collection
- min – Getting the minimum element of a collection
- max – Getting the maximum item in a collection
- reverse – Reverse the elements of the collection
- limit – Shrink the collection to the specified size
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:
- each
- walk
- filter
- reorganize
- map
- sort
- sortBy
- sortDesc
- sortDescBy
- reverse
- limit
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:
- Predicates
- Comparators
- Converters
- Reorganizers
- Consumers
- Aggregation
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
- notResistance – Passing all values
- notNull – Checking values for emptiness
- eachEven – Passing even call items
- nth – Passing specified elements
- equal – Equivalence check
- lockDuplicated – Locking duplicate values
- lessThan – Checking a value for the "less" condition
- lessOrEqual – Checking a value for a "less than or equal" condition
- greaterThan – Checking a value for the "greater than" condition
- greaterOrEqual – Checking a value for a "greater than or equal" condition
- not – Checking a value for inequality
- in – Checking a value for being in group of values
- notIn – Checking a value for absence in group of values
- where – Checking object property for equivalence
- whereNot – Checking object properties for inequality
- whereIn – Checking a property of an object for being in group of values
- whereNotIn – Checking an object property for absence in group of values
- whereGreaterThan – Checking an object property for the "greater than" condition
- whereLessThan – Checking an object property for the "less" condition
- wheregGreaterOrEqual – Checking an object property for a "greater than or equal" condition
- whereLessOrEqual – Checking an object property for a "less than or equal" condition
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
- objectPropertyComparator – Comparing object properties
- callbackComparator – Defining a function to compare values
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
- toProperties – Converting each item in a collection to an associative array
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
- random – Getting random elements of a collection
- chunk – Splitting into multiple collections of a specified size
- collapse – Getting a collection without additional nesting levels
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
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
- addToSet
- agv
- count
- first
- last
- max
- min
- sum
- addAggregator
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
ext-json Version *