Library of array functions for manipulating and extracting data from arrays or 'sets' of data.
Hash
provides an improved interface, more consistent and predictable set of features over Set
. While it lacks the spotty support for pseudo Xpath, its more fully featured dot notation provides similar features in a more consistent implementation.
Callback function for filtering.
Check a key against a token.
Checks whether $data matches the attribute patterns
Merge helper function to reduce duplicated code between merge() and expand().
Perform a simple insert/remove operation.
Split token conditions
Helper method for sort() Squashes an array to a single hash so it can be sorted.
Apply a callback to a set of extracted values using $function
. The function will get the extracted values as the first argument.
Test whether a given path exists in $data. This method uses the same path syntax as Hash::extract()
Creates an associative array using $keyPath
as the path to build its keys, and optionally $valuePath
as path to get the values. If $valuePath
is not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in $groupPath
.
Determines if one array contains the exact keys and values of another.
Computes the difference between two complex arrays. This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
Expands a flat array to a nested array.
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
Recursively filters a data set.
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
Returns a formatted series of values extracted from $data
, using $format
as the format and $paths
as the values to extract.
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
Insert $values into an array with the given $path. You can use {n}
and {s}
elements to insert $data multiple times.
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
Counts the dimensions of all array elements. Useful for finding the maximum number of dimensions in a mixed array.
This function can be thought of as a hybrid between PHP's array_merge
and array_merge_recursive
.
Merges the difference between $data and $compare onto $data.
Takes in a flat array and returns a nested array
Normalizes an array, and converts it to a standard format.
Checks to see if all the values in the array are numeric
Reduce a set of extracted values using $function
.
Remove data matching $path from the $data array. You can use {n}
and {s}
to remove multiple elements from $data.
Sorts an array by any value, determined by a Set-compatible path
_filter(mixed $var): bool
Callback function for filtering.
mixed
$var Array to filter.
bool
_matchToken(mixed $key, string $token): bool
Check a key against a token.
mixed
$key The key in the array being searched.
string
$token The token being matched.
bool
_matches(ArrayAccess|array $data, string $selector): bool
Checks whether $data matches the attribute patterns
ArrayAccess|array
$data Array of data to match.
string
$selector The patterns to match.
bool
_merge(array $stack, array $return): void
Merge helper function to reduce duplicated code between merge() and expand().
array
$stack The stack of operations to work with.
array
$return The return value to operate on.
void
_simpleOp(string $op, array $data, array<string> $path, mixed $values = null): array
Perform a simple insert/remove operation.
string
$op The operation to do.
array
$data The data to operate on.
array<string>
$path The path to work on.
mixed
$values optional The values to insert when doing inserts.
array
_splitConditions(string $token): array
Split token conditions
string
$token the token being splitted.
array
_squash(array $data, mixed $key = null): array
Helper method for sort() Squashes an array to a single hash so it can be sorted.
array
$data The data to squash.
mixed
$key optional The key for the data.
array
apply(array $data, string $path, callable $function): mixed
Apply a callback to a set of extracted values using $function
. The function will get the extracted values as the first argument.
You can easily count the results of an extract using apply(). For example to count the comments on an Article:
$count = Hash::apply($data, 'Article.Comment.{n}', 'count');
You could also use a function like array_sum
to sum the results.
$total = Hash::apply($data, '{n}.Item.price', 'array_sum');
array
$data The data to reduce.
string
$path The path to extract from $data.
callable
$function The function to call on each extracted value.
mixed
check(array $data, string $path): bool
Test whether a given path exists in $data. This method uses the same path syntax as Hash::extract()
Checking for paths that could target more than one element will make sure that at least one matching element exists.
array
$data The data to check.
string
$path The path to check for.
bool
combine(array $data, array<string>|string|null $keyPath, array<string>|string|null $valuePath = null, string|null $groupPath = null): array
Creates an associative array using $keyPath
as the path to build its keys, and optionally $valuePath
as path to get the values. If $valuePath
is not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in $groupPath
.
array
$data Array from where to extract keys and values
array<string>|string|null
$keyPath A dot-separated string.
array<string>|string|null
$valuePath optional A dot-separated string.
string|null
$groupPath optional A dot-separated string.
array
RuntimeException
contains(array $data, array $needle): bool
Determines if one array contains the exact keys and values of another.
array
$data The data to search through.
array
$needle The values to file in $data
bool
diff(array $data, array $compare): array
Computes the difference between two complex arrays. This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.
array
$data First value
array
$compare Second value
array
dimensions(array $data): int
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
If you have an un-even or heterogeneous array, consider using Hash::maxDimensions() to get the dimensions of the array.
array
$data Array to count dimensions on
int
expand(array $data, string $separator = '.'): array
Expands a flat array to a nested array.
For example, unflattens an array that was collapsed with Hash::flatten()
into a multi-dimensional array. So, ['0.Foo.Bar' => 'Far']
becomes [['Foo' => ['Bar' => 'Far']]]
.
array
$data Flattened array
string
$separator optional The delimiter used
array
extract(ArrayAccess|array $data, string $path): ArrayAccess|array
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
{n}
Matches any numeric key, or integer.{s}
Matches any string key.{*}
Matches any value.Foo
Matches any key with the exact same value.There are a number of attribute operators:
=
, !=
Equality. >
, <
, >=
, <=
Value comparison.=/.../
Regular expression pattern match.Given a set of User array data, from a $usersTable->find('all')
call:
1.User.name
Get the name of the user at index 1.{n}.User.name
Get the name of every user in the set of users.{n}.User[id].name
Get the name of every user with an id key.{n}.User[id>=2].name
Get the name of every user with an id key greater than or equal to 2.{n}.User[username=/^paul/]
Get User elements with username matching ^paul
.{n}.User[id=1].name
Get the Users name with id matching 1
.ArrayAccess|array
$data The data to extract from.
string
$path The path to extract.
ArrayAccess|array
filter(array $data, callable|array $callback = [Hash::class, '_filter']): array
Recursively filters a data set.
array
$data Either an array to filter, or value when in callback
callable|array
$callback optional A function to filter the data with. Defaults to static::_filter()
Which strips out all non-zero empty values.
array
flatten(array $data, string $separator = '.'): array
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
array
$data Array to flatten
string
$separator optional String used to separate array key elements in a path, defaults to '.'
array
format(array $data, array<string> $paths, string $format): array<string>|null
Returns a formatted series of values extracted from $data
, using $format
as the format and $paths
as the values to extract.
Usage:
$result = Hash::format($users, ['{n}.User.id', '{n}.User.name'], '%s : %s');
The $format
string can use any format options that vsprintf()
and sprintf()
do.
array
$data Source array from which to extract the data
array<string>
$paths An array containing one or more Hash::extract()-style key paths
string
$format Format string into which values will be inserted, see sprintf()
array<string>|null
get(ArrayAccess|array $data, array<string>|string|int|null $path, mixed $default = null): mixed
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
ArrayAccess|array
$data Array of data or object implementing \ArrayAccess interface to operate on.
array<string>|string|int|null
$path The path being searched for. Either a dot separated string, or an array of path segments.
mixed
$default optional The return value when the path does not exist
mixed
InvalidArgumentException
insert(array $data, string $path, mixed $values = null): array
Insert $values into an array with the given $path. You can use {n}
and {s}
elements to insert $data multiple times.
array
$data The data to insert into.
string
$path The path to insert at.
mixed
$values optional The values to insert.
array
map(array $data, string $path, callable $function): array
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
array
$data The data to map over, and extract data out of.
string
$path The path to extract for mapping over.
callable
$function The function to call on each extracted value.
array
maxDimensions(array $data): int
Counts the dimensions of all array elements. Useful for finding the maximum number of dimensions in a mixed array.
array
$data Array to count dimensions on
int
merge(array $data, mixed $merge): array
This function can be thought of as a hybrid between PHP's array_merge
and array_merge_recursive
.
The difference between this method and the built-in ones, is that if an array key contains another array, then Hash::merge() will behave in a recursive fashion (unlike array_merge
). But it will not act recursively for keys that contain scalar values (unlike array_merge_recursive
).
This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
array
$data Array to be merged
mixed
$merge Array to merge with. The argument and all trailing arguments will be array cast when merged
array
mergeDiff(array $data, array $compare): array
Merges the difference between $data and $compare onto $data.
array
$data The data to append onto.
array
$compare The data to compare and append onto.
array
nest(array $data, array<string, mixed> $options = []): array<array>
Takes in a flat array and returns a nested array
children
The key name to use in the resultset for children.idPath
The path to a key that identifies each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.id
parentPath
The path to a key that identifies the parent of each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.parent_id
root
The id of the desired top-most result.array
$data The data to nest.
array<string, mixed>
$options optional Options are:
array<array>
InvalidArgumentException
normalize(array $data, bool $assoc = true): array
Normalizes an array, and converts it to a standard format.
array
$data List to normalize
bool
$assoc optional If true, $data will be converted to an associative array.
array
numeric(array $data): bool
Checks to see if all the values in the array are numeric
array
$data The array to check.
bool
reduce(array $data, string $path, callable $function): mixed
Reduce a set of extracted values using $function
.
array
$data The data to reduce.
string
$path The path to extract from $data.
callable
$function The function to call on each extracted value.
mixed
remove(array $data, string $path): array
Remove data matching $path from the $data array. You can use {n}
and {s}
to remove multiple elements from $data.
array
$data The data to operate on
string
$path A path expression to use to remove.
array
sort(array $data, string $path, string|int $dir = 'asc', array<string, mixed>|string $type = 'regular'): array
Sorts an array by any value, determined by a Set-compatible path
asc
or \SORT_ASC Sort ascending.desc
or \SORT_DESC Sort descending.regular
For regular sorting (don't change types)numeric
Compare values numericallystring
Compare values as stringslocale
Compare items as strings, based on the current localenatural
Compare items as strings using "natural ordering" in a human friendly way Will sort foo10 below foo2 as an example.To do case insensitive sorting, pass the type as an array as follows:
Hash::sort($data, 'some.attribute', 'asc', ['type' => 'regular', 'ignoreCase' => true]);
When using the array form, type
defaults to 'regular'. The ignoreCase
option defaults to false
.
array
$data An array of data to sort
string
$path A Set-compatible path to the array value
string|int
$dir optional See directions above. Defaults to 'asc'.
array<string, mixed>|string
$type optional See direction types above. Defaults to 'regular'.
array
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.4/class-Cake.Utility.Hash.html