Hash

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.

package

Cake.Utility

Methods

Callback function for filtering.

_filter(array $var): boolean
static

Arguments

$var

array

Array to filter.

Response

boolean

Checks whether or not $data matches the attribute patterns

_matches(array $data,string $selector): boolean
static

Arguments

$data

array

Array of data to match.

$selector

string

The patterns to match.

Response

boolean

Fitness of expression.

Check a key against a token.

_matchToken(string $key,string $token): boolean
static

Arguments

$key

string

The key in the array being searched.

$token

string

The token being matched.

Response

boolean

Perform a simple insert/remove operation.

_simpleOp(string $op,array $data,array $path,mixed $values = null): array
static

Arguments

$op

string

The operation to do.

$data

array

The data to operate on.

$path

array

The path to work on.

$values

mixed

The values to insert when doing inserts.

Response

array

$data.

Helper method for sort() Squashes an array to a single hash so it can be sorted.

_squash(array $data,string $key = null): array
static

Arguments

$data

array

The data to squash.

$key

string

The key for the data.

Response

array

Apply a callback to a set of extracted values using `$function`.

apply(array $data,string $path,callable $function): mixed
static

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');

Arguments

$data

array

The data to reduce.

$path

string

The path to extract from $data.

$function

callable

The function to call on each extracted value.

Response

mixed

The results of the applied method.

Test whether or not a given path exists in $data.

check(array $data,string $path): boolean
static

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.

see \Hash::extract()

Arguments

$data

array

The data to check.

$path

string

The path to check for.

Response

boolean

Existence of path.

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`.

combine(array $data,string $keyPath,string $valuePath = null,string $groupPath = null): array
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine

Arguments

$data

array

Array from where to extract keys and values

$keyPath

string

A dot-separated string.

$valuePath

string

A dot-separated string.

$groupPath

string

A dot-separated string.

Response

array

Combined array

Determines if one array contains the exact keys and values of another.

contains(array $data,array $needle): boolean
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::contains

Arguments

$data

array

The data to search through.

$needle

array

The values to file in $data

Response

boolean

true if $data contains $needle, false otherwise

Computes the difference between two complex arrays.

diff(array $data,array $compare): array
static

This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.

link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::diff

Arguments

$data

array

First value

$compare

array

Second value

Response

array

Returns the key => value pairs that are not common in $data and $compare The expression for this function is ($data - $compare) + ($compare - ($data - $compare))

Counts the dimensions of an array.

dimensions(array $data): integer
static

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.

link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions

Arguments

$data

array

Response

integer

The number of dimensions in $data

Expand/unflattens an string to an array

expand(array $data,string $separator = '.'): array
static

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'))).

Arguments

$data

array

Flattened array

$separator

string

The delimiter used

Response

array

Gets the values from an array matching the $path expression.

extract(array $data,string $path): array
static

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.

Arguments

$data

array

The data to extract from.

$path

string

The path to extract.

Response

array

An array of the extracted values. Returns an empty array if there are no matches.

Recursively filters a data set.

filter(array $data,callable $callback = array('self', '_filter')): array
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::filter

Arguments

$data

array

Either an array to filter, or value when in callback

$callback

callable

A function to filter the data with. Defaults to self::_filter() Which strips out all non-zero empty values.

Response

array

Filtered array

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').)

flatten(array $data,string $separator = '.'): array
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten

Arguments

$data

array

Array to flatten

$separator

string

String used to separate array key elements in a path, defaults to '.'

Response

array

Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.

format(array $data,string $paths,string $format): array|null
static

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.

link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format

see \sprintf()\Hash::extract()

Arguments

$data

array

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()

Response

array|null

An array of strings extracted from $path and formatted with $format

Get a single value specified by $path out of $data.

get(array $data,string|array $path): mixed
static

Does not support the full dot notation feature set, but is faster for simple read operations.

Arguments

$data

array

Array of data to operate on.

$path

string|array

The path being searched for. Either a dot separated string, or an array of path segments.

Response

mixed

The value fetched from the array, or null.

Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.

insert(array $data,string $path,array $values = null): array
static

Arguments

$data

array

The data to insert into.

$path

string

The path to insert at.

$values

array

The values to insert.

Response

array

The data with $values inserted.

Map a callback across all elements in a set.

map(array $data,string $path,callable $function): array
static

Can be provided a path to only modify slices of the set.

Arguments

$data

array

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.

Response

array

An array of the modified values.

Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.

maxDimensions(array $data): integer
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions

Arguments

$data

array

Array to count dimensions on

Response

integer

The maximum number of dimensions in $data

This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.

merge(array $data,mixed $merge): array
static

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.

link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge

Arguments

$data

array

Array to be merged

$merge

mixed

Array to merge with. The argument and all trailing arguments will be array cast when merged

Response

array

Merged array

Merges the difference between $data and $push onto $data.

mergeDiff(array $data,array $compare): array
static

Arguments

$data

array

The data to append onto.

$compare

array

The data to compare and append onto.

Response

array

The merged array.

Takes in a flat array and returns a nested array

nest(array $data,array $options = array()): array
static

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.
see \Hash::extract()

Arguments

$data

array

The data to nest.

$options

array

Options are:

Response

array

of results, nested

Normalizes an array, and converts it to a standard format.

normalize(array $data,boolean $assoc = true): array
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize

Arguments

$data

array

List to normalize

$assoc

boolean

If true, $data will be converted to an associative array.

Response

array

Checks to see if all the values in the array are numeric

numeric(array $data): boolean
static
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric

Arguments

$data

array

Response

boolean

true if values are numeric, false otherwise

Reduce a set of extracted values using `$function`.

reduce(array $data,string $path,callable $function): mixed
static

Arguments

$data

array

The data to reduce.

$path

string

The path to extract from $data.

$function

callable

The function to call on each extracted value.

Response

mixed

The reduced value.

Remove data matching $path from the $data array.

remove(array $data,string $path): array
static

You can use {n} and {s} to remove multiple elements from $data.

Arguments

$data

array

The data to operate on

$path

string

A path expression to use to remove.

Response

array

The modified array.

Sorts an array by any value, determined by a Set-compatible path

sort(array $data,string $path,string $dir,string $type = 'regular'): array
static

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'
link

http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort

Arguments

$data

array

An array of data to sort

$path

string

A Set-compatible path to the array value

$dir

string

See directions above.

$type

string

See direction types above. Defaults to 'regular'.

Response

array

Sorted array of data