Hash
in package
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.
Table of Contents
Methods
- apply() : mixed
- Apply a callback to a set of extracted values using `$function`.
- check() : bool
- Test whether or not a given path exists in $data.
- combine() : array<string|int, mixed>
- 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`.
- contains() : bool
- Determines if one array contains the exact keys and values of another.
- diff() : array<string|int, mixed>
- Computes the difference between two complex arrays.
- dimensions() : int
- Counts the dimensions of an array.
- expand() : array<string|int, mixed>
- Expand/unflattens an string to an array
- extract() : array<string|int, mixed>
- Gets the values from an array matching the $path expression.
- filter() : array<string|int, mixed>
- Recursively filters a data set.
- flatten() : array<string|int, mixed>
- Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes array('0.Foo.Bar' => 'Far').)
- format() : array<string|int, mixed>|null
- Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.
- get() : mixed
- Get a single value specified by $path out of $data.
- insert() : array<string|int, mixed>
- Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.
- map() : array<string|int, mixed>
- Map a callback across all elements in a set.
- maxDimensions() : int
- Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.
- merge() : array<string|int, mixed>
- This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
- mergeDiff() : array<string|int, mixed>
- Merges the difference between $data and $push onto $data.
- nest() : array<string|int, mixed>
- Takes in a flat array and returns a nested array
- normalize() : array<string|int, mixed>
- Normalizes an array, and converts it to a standard format.
- numeric() : bool
- Checks to see if all the values in the array are numeric
- reduce() : mixed
- Reduce a set of extracted values using `$function`.
- remove() : array<string|int, mixed>
- Remove data matching $path from the $data array.
- sort() : array<string|int, mixed>
- Sorts an array by any value, determined by a Set-compatible path
- _filter() : bool
- Callback function for filtering.
- _matches() : bool
- Checks whether or not $data matches the attribute patterns
- _matchToken() : bool
- Check a key against a token.
- _simpleOp() : array<string|int, mixed>
- Perform a simple insert/remove operation.
- _squash() : array<string|int, mixed>
- Helper method for sort() Squashes an array to a single hash so it can be sorted.
Methods
apply()
Apply a callback to a set of extracted values using `$function`.
public
static apply(array<string|int, mixed> $data, string $path, callable $function) : mixed
The function will get the extracted values as the first argument.
Example
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');
Parameters
- $data : array<string|int, mixed>
-
The data to reduce.
- $path : string
-
The path to extract from $data.
- $function : callable
-
The function to call on each extracted value.
Return values
mixed —The results of the applied method.
check()
Test whether or not a given path exists in $data.
public
static check(array<string|int, mixed> $data, string $path) : bool
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.
Parameters
- $data : array<string|int, mixed>
-
The data to check.
- $path : string
-
The path to check for.
Tags
Return values
bool —Existence of path.
combine()
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`.
public
static combine(array<string|int, mixed> $data, string $keyPath[, string $valuePath = null ][, string $groupPath = null ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
Array from where to extract keys and values
- $keyPath : string
-
A dot-separated string.
- $valuePath : string = null
-
A dot-separated string.
- $groupPath : string = null
-
A dot-separated string.
Tags
Return values
array<string|int, mixed> —Combined array
contains()
Determines if one array contains the exact keys and values of another.
public
static contains(array<string|int, mixed> $data, array<string|int, mixed> $needle) : bool
Parameters
- $data : array<string|int, mixed>
-
The data to search through.
- $needle : array<string|int, mixed>
-
The values to file in $data
Tags
Return values
bool —true if $data contains $needle, false otherwise
diff()
Computes the difference between two complex arrays.
public
static diff(array<string|int, mixed> $data, array<string|int, mixed> $compare) : array<string|int, mixed>
This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.
Parameters
- $data : array<string|int, mixed>
-
First value
- $compare : array<string|int, mixed>
-
Second value
Tags
Return values
array<string|int, mixed> —Returns the key => value pairs that are not common in $data and $compare The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
dimensions()
Counts the dimensions of an array.
public
static dimensions(array<string|int, mixed> $data) : int
Only considers the dimension of the first element in the array.
If you have an un-even or heterogenous array, consider using Hash::maxDimensions() to get the dimensions of the array.
Parameters
- $data : array<string|int, mixed>
Tags
Return values
int —The number of dimensions in $data
expand()
Expand/unflattens an string to an array
public
static expand(array<string|int, mixed> $data[, string $separator = '.' ]) : array<string|int, mixed>
For example, unflattens an array that was collapsed with Hash::flatten()
into a multi-dimensional array. So, array('0.Foo.Bar' => 'Far')
becomes
array(array('Foo' => array('Bar' => 'Far')))
.
Parameters
- $data : array<string|int, mixed>
-
Flattened array
- $separator : string = '.'
-
The delimiter used
Return values
array<string|int, mixed>extract()
Gets the values from an array matching the $path expression.
public
static extract(array<string|int, mixed> $data, string $path) : array<string|int, mixed>
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. -
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 $User->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]
Get the name of every user with an id key. -
{n}.User[id>=2]
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
.
Parameters
- $data : array<string|int, mixed>
-
The data to extract from.
- $path : string
-
The path to extract.
Return values
array<string|int, mixed> —An array of the extracted values. Returns an empty array if there are no matches.
filter()
Recursively filters a data set.
public
static filter(array<string|int, mixed> $data[, callable $callback = array('self', '_filter') ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
Either an array to filter, or value when in callback
- $callback : callable = array('self', '_filter')
-
A function to filter the data with. Defaults to
self::_filter()
Which strips out all non-zero empty values.
Tags
Return values
array<string|int, mixed> —Filtered array
flatten()
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes array('0.Foo.Bar' => 'Far').)
public
static flatten(array<string|int, mixed> $data[, string $separator = '.' ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
Array to flatten
- $separator : string = '.'
-
String used to separate array key elements in a path, defaults to '.'
Tags
Return values
array<string|int, mixed>format()
Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.
public
static format(array<string|int, mixed> $data, string $paths, string $format) : array<string|int, mixed>|null
Usage:
{{{ $result = Hash::format($users, array('{n}.User.id', '{n}.User.name'), '%s : %s'); }}}
The $format
string can use any format options that vsprintf()
and sprintf()
do.
Parameters
- $data : array<string|int, mixed>
-
Source array from which to extract the data
- $paths : string
-
An array containing one or more Hash::extract()-style key paths
- $format : string
-
Format string into which values will be inserted, see sprintf()
Tags
Return values
array<string|int, mixed>|null —An array of strings extracted from $path
and formatted with $format
get()
Get a single value specified by $path out of $data.
public
static get(array<string|int, mixed> $data, string|array<string|int, mixed> $path) : mixed
Does not support the full dot notation feature set, but is faster for simple read operations.
Parameters
- $data : array<string|int, mixed>
-
Array of data to operate on.
- $path : string|array<string|int, mixed>
-
The path being searched for. Either a dot separated string, or an array of path segments.
Return values
mixed —The value fetched from the array, or null.
insert()
Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.
public
static insert(array<string|int, mixed> $data, string $path[, array<string|int, mixed> $values = null ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
The data to insert into.
- $path : string
-
The path to insert at.
- $values : array<string|int, mixed> = null
-
The values to insert.
Return values
array<string|int, mixed> —The data with $values inserted.
map()
Map a callback across all elements in a set.
public
static map(array<string|int, mixed> $data, string $path, callable $function) : array<string|int, mixed>
Can be provided a path to only modify slices of the set.
Parameters
- $data : array<string|int, mixed>
-
The data to map over, and extract data out of.
- $path : string
-
The path to extract for mapping over.
- $function : callable
-
The function to call on each extracted value.
Return values
array<string|int, mixed> —An array of the modified values.
maxDimensions()
Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.
public
static maxDimensions(array<string|int, mixed> $data) : int
Parameters
- $data : array<string|int, mixed>
-
Array to count dimensions on
Tags
Return values
int —The maximum number of dimensions in $data
merge()
This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
public
static merge(array<string|int, mixed> $data, mixed $merge) : array<string|int, mixed>
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
).
Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
Parameters
- $data : array<string|int, mixed>
-
Array to be merged
- $merge : mixed
-
Array to merge with. The argument and all trailing arguments will be array cast when merged
Tags
Return values
array<string|int, mixed> —Merged array
mergeDiff()
Merges the difference between $data and $push onto $data.
public
static mergeDiff(array<string|int, mixed> $data, array<string|int, mixed> $compare) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
The data to append onto.
- $compare : array<string|int, mixed>
-
The data to compare and append onto.
Return values
array<string|int, mixed> —The merged array.
nest()
Takes in a flat array and returns a nested array
public
static nest(array<string|int, mixed> $data[, array<string|int, mixed> $options = array() ]) : array<string|int, mixed>
Options:
-
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.
Parameters
- $data : array<string|int, mixed>
-
The data to nest.
- $options : array<string|int, mixed> = array()
-
Options are:
Tags
Return values
array<string|int, mixed> —of results, nested
normalize()
Normalizes an array, and converts it to a standard format.
public
static normalize(array<string|int, mixed> $data[, bool $assoc = true ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
List to normalize
- $assoc : bool = true
-
If true, $data will be converted to an associative array.
Tags
Return values
array<string|int, mixed>numeric()
Checks to see if all the values in the array are numeric
public
static numeric(array<string|int, mixed> $data) : bool
Parameters
- $data : array<string|int, mixed>
Tags
Return values
bool —true if values are numeric, false otherwise
reduce()
Reduce a set of extracted values using `$function`.
public
static reduce(array<string|int, mixed> $data, string $path, callable $function) : mixed
Parameters
- $data : array<string|int, mixed>
-
The data to reduce.
- $path : string
-
The path to extract from $data.
- $function : callable
-
The function to call on each extracted value.
Return values
mixed —The reduced value.
remove()
Remove data matching $path from the $data array.
public
static remove(array<string|int, mixed> $data, string $path) : array<string|int, mixed>
You can use {n}
and {s}
to remove multiple elements
from $data.
Parameters
- $data : array<string|int, mixed>
-
The data to operate on
- $path : string
-
A path expression to use to remove.
Return values
array<string|int, mixed> —The modified array.
sort()
Sorts an array by any value, determined by a Set-compatible path
public
static sort(array<string|int, mixed> $data, string $path, string $dir[, string $type = 'regular' ]) : array<string|int, mixed>
Sort directions
-
asc
Sort ascending. -
desc
Sort descending.
Sort types
-
regular
For regular sorting (don't change types) -
numeric
Compare values numerically -
string
Compare values as strings -
natural
Compare items as strings using "natural ordering" in a human friendly way. Will sort foo10 below foo2 as an example. Requires PHP 5.4 or greater or it will fallback to 'regular'
Parameters
- $data : array<string|int, mixed>
-
An array of data to sort
- $path : string
-
A Set-compatible path to the array value
- $dir : string
-
See directions above.
- $type : string = 'regular'
-
See direction types above. Defaults to 'regular'.
Tags
Return values
array<string|int, mixed> —Sorted array of data
_filter()
Callback function for filtering.
protected
static _filter(array<string|int, mixed> $var) : bool
Parameters
- $var : array<string|int, mixed>
-
Array to filter.
Return values
bool_matches()
Checks whether or not $data matches the attribute patterns
protected
static _matches(array<string|int, mixed> $data, string $selector) : bool
Parameters
- $data : array<string|int, mixed>
-
Array of data to match.
- $selector : string
-
The patterns to match.
Return values
bool —Fitness of expression.
_matchToken()
Check a key against a token.
protected
static _matchToken(string $key, string $token) : bool
Parameters
- $key : string
-
The key in the array being searched.
- $token : string
-
The token being matched.
Return values
bool_simpleOp()
Perform a simple insert/remove operation.
protected
static _simpleOp(string $op, array<string|int, mixed> $data, array<string|int, mixed> $path[, mixed $values = null ]) : array<string|int, mixed>
Parameters
- $op : string
-
The operation to do.
- $data : array<string|int, mixed>
-
The data to operate on.
- $path : array<string|int, mixed>
-
The path to work on.
- $values : mixed = null
-
The values to insert when doing inserts.
Return values
array<string|int, mixed> —$data.
_squash()
Helper method for sort() Squashes an array to a single hash so it can be sorted.
protected
static _squash(array<string|int, mixed> $data[, string $key = null ]) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
The data to squash.
- $key : string = null
-
The key for the data.