CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeNumber
  • CakeTime
  • ClassRegistry
  • Debugger
  • File
  • Folder
  • Hash
  • Inflector
  • ObjectCollection
  • Sanitize
  • Security
  • Set
  • String
  • Validation
  • Xml

Class 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
Copyright: Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: Cake/Utility/Hash.php

Method Summary

  • _filter() protected static
    Callback function for filtering.
  • _matchToken() protected static
    Check a key against a token.
  • _matches() protected static
    Checks whether or not $data matches the attribute patterns
  • _simpleOp() protected static
    Perform a simple insert/remove operation.
  • _squash() protected static

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

  • apply() public static

    Apply a callback to a set of extracted values using $function. The function will get the extracted values as the first argument.

  • check() public static

    Test whether or not a given path exists in $data. This method uses the same path syntax as Hash::extract()

  • combine() public static

    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() public static
    Determines if one array contains the exact keys and values of another.
  • diff() public static

    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.

  • dimensions() public static

    Counts the dimensions of an array. Only considers the dimension of the first element in the array.

  • expand() public static
    Expand/unflattens an string to an array
  • extract() public static

    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:

  • filter() public static
    Recursively filters a data set.
  • flatten() public static

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

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

  • get() public static

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

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

  • map() public static

    Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.

  • maxDimensions() public static

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

  • merge() public static
    This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive.
  • mergeDiff() public static
    Merges the difference between $data and $push onto $data.
  • nest() public static
    Takes in a flat array and returns a nested array
  • normalize() public static
    Normalizes an array, and converts it to a standard format.
  • numeric() public static
    Checks to see if all the values in the array are numeric
  • reduce() public static
    Reduce a set of extracted values using $function.
  • remove() public static

    Remove data matching $path from the $data array. You can use {n} and {s} to remove multiple elements from $data.

  • sort() public static
    Sorts an array by any value, determined by a Set-compatible path

Method Detail

_filter() protected static ¶

_filter( array $var )

Callback function for filtering.

Parameters
array $var
Array to filter.
Returns
boolean

_matchToken() protected static ¶

_matchToken( string $key , string $token )

Check a key against a token.

Parameters
string $key
The key in the array being searched.
string $token
The token being matched.
Returns
boolean

_matches() protected static ¶

_matches( array $data , string $selector )

Checks whether or not $data matches the attribute patterns

Parameters
array $data
Array of data to match.
string $selector
The patterns to match.
Returns
boolean
Fitness of expression.

_simpleOp() protected static ¶

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

Perform a simple insert/remove operation.

Parameters
string $op
The operation to do.
array $data
The data to operate on.
array $path
The path to work on.
mixed $values optional null
The values to insert when doing inserts.
Returns
array
$data.

_squash() protected static ¶

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

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

Parameters
array $data
The data to squash.
string $key optional null
The key for the data.
Returns
array

apply() public static ¶

apply( array $data , string $path , $function )

Apply a callback to a set of extracted values using $function. 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
array $data
The data to reduce.
string $path
The path to extract from $data.
$function
Returns
mixed
The results of the applied method.

check() public static ¶

check( array $data , string $path )

Test whether or not 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.

Parameters
array $data
The data to check.
string $path
The path to check for.
Returns
boolean
Existence of path.
See
Hash::extract()

combine() public static ¶

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

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.

Parameters
array $data
Array from where to extract keys and values
string $keyPath
A dot-separated string.
string $valuePath optional null
A dot-separated string.
string $groupPath optional null
A dot-separated string.
Returns
array
Combined array
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine

contains() public static ¶

contains( array $data , array $needle )

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

Parameters
array $data
The data to search through.
array $needle
The values to file in $data
Returns
boolean
true if $data contains $needle, false otherwise
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::contains

diff() public static ¶

diff( array $data , array $compare )

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.

Parameters
array $data
First value
array $compare
Second value
Returns
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))


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

dimensions() public static ¶

dimensions( array $data )

Counts the dimensions of an array. Only considers the dimension of the first element in the array.

If you have an un-even or hetrogenous array, consider using Hash::maxDimensions() to get the dimensions of the array.

Parameters
array $data
$array Array to count dimensions on
Returns
integer
The number of dimensions in $data
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions

expand() public static ¶

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

Expand/unflattens an string to an array

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
array $data
Flattened array
string $separator optional '.'
The delimiter used
Returns
array

extract() public static ¶

extract( array $data , string $path )

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.
  • 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
array $data
The data to extract from.
string $path
The path to extract.
Returns
array

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


filter() public static ¶

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

Recursively filters a data set.

Parameters
array $data
Either an array to filter, or value when in callback
callable $callback optional array('self', '_filter')

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

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

flatten() public static ¶

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

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

Parameters
array $data
Array to flatten
string $separator optional '.'
String used to separate array key elements in a path, defaults to '.'
Returns
array
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten

format() public static ¶

format( array $data , array $paths , string $format )

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

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
array $data
Source array from which to extract the data
array $paths
An array containing one or more Hash::extract()-style key paths
string $format
Format string into which values will be inserted, see sprintf()
Returns
array
An array of strings extracted from $path and formatted with $format
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
See
sprintf()
Hash::extract()

get() public static ¶

get( array $data , string|array $path )

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.

Parameters
array $data
Array of data to operate on.
string|array $path

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

Returns
mixed
The value fetched from the array, or null.

insert() public static ¶

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

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

Parameters
array $data
The data to insert into.
string $path
The path to insert at.
array $values optional null
The values to insert.
Returns
array
The data with $values inserted.

map() public static ¶

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

Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.

Parameters
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.
Returns
array
An array of the modified values.

maxDimensions() public static ¶

maxDimensions( array $data )

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

Parameters
array $data
Array to count dimensions on
Returns
integer
The maximum number of dimensions in $data
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions

merge() public static ¶

merge( array $data , mixed $merge )

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

Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.

Parameters
array $data
Array to be merged
mixed $merge
Array to merge with. The argument and all trailing arguments will be array cast when merged
Returns
array
Merged array
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge

mergeDiff() public static ¶

mergeDiff( array $data , array $compare )

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

Parameters
array $data
The data to append onto.
array $compare
The data to compare and append onto.
Returns
array
The merged array.

nest() public static ¶

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

Takes in a flat array and returns a nested array

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
array $data
The data to nest.
array $options optional array()
Options are:
Returns
array
of results, nested
See
Hash::extract()

normalize() public static ¶

normalize( array $data , boolean $assoc = true )

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

Parameters
array $data
List to normalize
boolean $assoc optional true
If true, $data will be converted to an associative array.
Returns
array
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize

numeric() public static ¶

numeric( array $data )

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

Parameters
array $data
$array The array to check.
Returns
boolean
true if values are numeric, false otherwise
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric

reduce() public static ¶

reduce( array $data , string $path , $function )

Reduce a set of extracted values using $function.

Parameters
array $data
The data to reduce.
string $path
The path to extract from $data.
$function
Returns
mixed
The reduced value.

remove() public static ¶

remove( array $data , string $path )

Remove data matching $path from the $data array. You can use {n} and {s} to remove multiple elements from $data.

Parameters
array $data
The data to operate on
string $path
A path expression to use to remove.
Returns
array
The modified array.

sort() public static ¶

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

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

Sort directions

  • asc Sort ascending.
  • desc Sort descending.

Sort types

  • numeric Sort by numeric value.
  • regular Sort by numeric value.
  • string Sort by numeric value.
  • natural Sort by natural order. Requires PHP 5.4 or greater.
Parameters
array $data
An array of data to sort
string $path
A Set-compatible path to the array value
string $dir
See directions above.
string $type optional 'regular'
See direction types above. Defaults to 'regular'.
Returns
array
Sorted array of data
Link
http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs