3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Provides a collection of static methods for array manipulation.
32 * @copyright CiviCRM LLC (c) 2004-2015
34 class CRM_Utils_Array
{
37 * Returns $list[$key] if such element exists, or a default value otherwise.
39 * If $list is not actually an array at all, then the default value is
44 * Key value to look up in the array.
46 * Array from which to look up a value.
47 * @param mixed $default
48 * (optional) Value to return $list[$key] does not exist.
51 * Can return any type, since $list might contain anything.
53 public static function value($key, $list, $default = NULL) {
54 if (is_array($list)) {
55 return array_key_exists($key, $list) ?
$list[$key] : $default;
61 * Recursively searches an array for a key, returning the first value found.
63 * If $params[$key] does not exist and $params contains arrays, descend into
64 * each array in a depth-first manner, in array iteration order.
66 * @param array $params
67 * The array to be searched.
69 * The key to search for.
72 * The value of the key, or null if the key is not found.
74 public static function retrieveValueRecursive(&$params, $key) {
75 if (!is_array($params)) {
78 elseif ($value = CRM_Utils_Array
::value($key, $params)) {
82 foreach ($params as $subParam) {
83 if (is_array($subParam) &&
84 $value = self
::retrieveValueRecursive($subParam, $key)
94 * Wraps and slightly changes the behavior of PHP's array_search().
96 * This function reproduces the behavior of array_search() from PHP prior to
97 * version 4.2.0, which was to return NULL on failure. This function also
98 * checks that $list is an array before attempting to search it.
101 * @param mixed $value
102 * The value to search for.
104 * The array to be searched.
106 * @return int|string|null
107 * Returns the key, which could be an int or a string, or NULL on failure.
109 public static function key($value, &$list) {
110 if (is_array($list)) {
111 $key = array_search($value, $list);
113 // array_search returns key if found, false otherwise
114 // it may return values like 0 or empty string which
115 // evaluates to false
116 // hence we must use identical comparison operator
117 return ($key === FALSE) ?
NULL : $key;
123 * Builds an XML fragment representing an array.
125 * Depending on the nature of the keys of the array (and its sub-arrays,
126 * if any) the XML fragment may not be valid.
129 * The array to be serialized.
131 * (optional) Indentation depth counter.
132 * @param string $seperator
133 * (optional) String to be appended after open/close tags.
137 * XML fragment representing $list.
139 public static function &xml(&$list, $depth = 1, $seperator = "\n") {
141 foreach ($list as $name => $value) {
142 $xml .= str_repeat(' ', $depth * 4);
143 if (is_array($value)) {
144 $xml .= "<{$name}>{$seperator}";
145 $xml .= self
::xml($value, $depth +
1, $seperator);
146 $xml .= str_repeat(' ', $depth * 4);
147 $xml .= "</{$name}>{$seperator}";
150 // make sure we escape value
151 $value = self
::escapeXML($value);
152 $xml .= "<{$name}>$value</{$name}>{$seperator}";
159 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
161 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
164 * @param string $value
165 * String to be sanitized.
168 * Sanitized version of $value.
170 public static function escapeXML($value) {
175 $src = array('&', '<', '>', '\ 1');
176 $dst = array('&', '<', '>', ',');
179 return str_replace($src, $dst, $value);
183 * Converts a nested array to a flat array.
185 * The nested structure is preserved in the string values of the keys of the
188 * Example nested array:
213 * Corresponding flattened array:
219 * [asdf.merp] => bleep
220 * [asdf.quack.0] => 1
221 * [asdf.quack.1] => 2
222 * [asdf.quack.2] => 3
227 * Array to be flattened.
230 * @param string $prefix
231 * (optional) String to prepend to keys.
232 * @param string $seperator
233 * (optional) String that separates the concatenated keys.
235 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
236 foreach ($list as $name => $value) {
237 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
238 if (is_array($value)) {
239 self
::flatten($value, $flat, $newPrefix, $seperator);
242 if (!empty($value)) {
243 $flat[$newPrefix] = $value;
250 * Converts an array with path-like keys into a tree of arrays.
252 * This function is the inverse of CRM_Utils_Array::flatten().
254 * @param string $delim
257 * A one-dimensional array indexed by string keys
262 public function unflatten($delim, &$arr) {
264 foreach ($arr as $key => $value) {
265 $path = explode($delim, $key);
267 while (count($path) > 1) {
268 $key = array_shift($path);
269 if (!isset($node[$key])) {
270 $node[$key] = array();
272 $node = &$node[$key];
275 $key = array_shift($path);
276 $node[$key] = $value;
284 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
285 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
286 * exist but they are not both arrays, the value from $a1 overrides the
287 * value from $a2 and the value from $a2 is discarded.
290 * First array to be merged.
292 * Second array to be merged.
297 public static function crmArrayMerge($a1, $a2) {
307 foreach ($a1 as $key => $value) {
308 if (array_key_exists($key, $a2) &&
309 is_array($a2[$key]) && is_array($a1[$key])
311 $a3[$key] = array_merge($a1[$key], $a2[$key]);
314 $a3[$key] = $a1[$key];
318 foreach ($a2 as $key => $value) {
319 if (array_key_exists($key, $a1)) {
320 // already handled in above loop
323 $a3[$key] = $a2[$key];
330 * Determines whether an array contains any sub-arrays.
333 * The array to inspect.
336 * True if $list contains at least one sub-array, false otherwise.
338 public static function isHierarchical(&$list) {
339 foreach ($list as $n => $v) {
351 * TRUE if $subset is a subset of $superset
353 public static function isSubset($subset, $superset) {
354 foreach ($subset as $expected) {
355 if (!in_array($expected, $superset)) {
363 * Searches an array recursively in an optionally case-insensitive manner.
365 * @param string $value
366 * Value to search for.
367 * @param array $params
368 * Array to search within.
369 * @param bool $caseInsensitive
370 * (optional) Whether to search in a case-insensitive manner.
373 * True if $value was found, false otherwise.
375 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
376 foreach ($params as $item) {
377 if (is_array($item)) {
378 $ret = crmInArray($value, $item, $caseInsensitive);
381 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
391 * convert associative array names to values.
394 * This function is used by both the web form layer and the api. Note that
395 * the api needs the name => value conversion, also the view layer typically
396 * requires value => name conversion
398 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
399 $id = $property . '_id';
401 $src = $reverse ?
$property : $id;
402 $dst = $reverse ?
$id : $property;
404 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
408 $look = $reverse ?
array_flip($lookup) : $lookup;
410 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
412 foreach ($look as $k => $v) {
413 $newLook[trim($k, ".")] = $v;
418 if (is_array($look)) {
419 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
424 $tempLook = array_change_key_case($look, CASE_LOWER
);
426 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
431 * Checks whether an array is empty.
433 * An array is empty if its values consist only of NULL and empty sub-arrays.
434 * Containing a non-NULL value or non-empty array makes an array non-empty.
436 * If something other than an array is passed, it is considered to be empty.
438 * If nothing is passed at all, the default value provided is empty.
440 * @param array $array
441 * (optional) Array to be checked for emptiness.
444 * True if the array is empty.
446 public static function crmIsEmptyArray($array = array()) {
447 if (!is_array($array)) {
450 foreach ($array as $element) {
451 if (is_array($element)) {
452 if (!self
::crmIsEmptyArray($element)) {
456 elseif (isset($element)) {
464 * Sorts an associative array of arrays by an attribute using strnatcmp().
466 * @param array $array
467 * Array to be sorted.
468 * @param string $field
469 * Name of the attribute used for sorting.
474 public static function crmArraySortByField($array, $field) {
475 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
476 uasort($array, create_function('$a,$b', $code));
481 * Recursively removes duplicate values from a multi-dimensional array.
483 * @param array $array
484 * The input array possibly containing duplicate values.
487 * The input array with duplicate values removed.
489 public static function crmArrayUnique($array) {
490 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
491 foreach ($result as $key => $value) {
492 if (is_array($value)) {
493 $result[$key] = self
::crmArrayUnique($value);
500 * Sorts an array and maintains index association (with localization).
502 * Uses Collate from the PECL "intl" package, if available, for UTF-8
503 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
505 * On Debian/Ubuntu: apt-get install php5-intl
507 * @param array $array
508 * (optional) Array to be sorted.
513 public static function asort($array = array()) {
514 $lcMessages = CRM_Utils_System
::getUFLocale();
516 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
517 $collator = new Collator($lcMessages . '.utf8');
518 $collator->asort($array);
521 // This calls PHP's built-in asort().
529 * Unsets an arbitrary list of array elements from an associative array.
531 * @param array $items
532 * The array from which to remove items.
535 * When passed a string, unsets $items[$key].
536 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
538 public static function remove(&$items) {
539 foreach (func_get_args() as $n => $key) {
540 // Skip argument 0 ($items) by testing $n for truth.
541 if ($n && is_array($key)) {
542 foreach ($key as $k) {
553 * Builds an array-tree which indexes the records in an array.
555 * @param string[] $keys
556 * Properties by which to index.
557 * @param object|array $records
560 * Multi-dimensional array, with one layer for each key.
562 public static function index($keys, $records) {
563 $final_key = array_pop($keys);
566 foreach ($records as $record) {
568 foreach ($keys as $key) {
569 if (is_array($record)) {
570 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
573 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
575 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
576 $node[$keyvalue] = array();
578 $node = &$node[$keyvalue];
580 if (is_array($record)) {
581 $node[$record[$final_key]] = $record;
584 $node[$record->{$final_key}] = $record;
591 * Iterates over a list of records and returns the value of some property.
593 * @param string $prop
594 * Property to retrieve.
595 * @param array|object $records
599 * Keys are the original keys of $records; values are the $prop values.
601 public static function collect($prop, $records) {
603 if (is_array($records)) {
604 foreach ($records as $key => $record) {
605 if (is_object($record)) {
606 $result[$key] = $record->{$prop};
609 $result[$key] = $record[$prop];
617 * Iterates over a list of objects and executes some method on each.
620 * - This is like array_map(), except it executes the objects' method
621 * instead of a free-form callable.
622 * - This is like Array::collect(), except it uses a method
623 * instead of a property.
625 * @param string $method
626 * The method to execute.
627 * @param array|Traversable $objects
630 * An optional list of arguments to pass to the method.
633 * Keys are the original keys of $objects; values are the method results.
635 public static function collectMethod($method, $objects, $args = array()) {
637 if (is_array($objects)) {
638 foreach ($objects as $key => $object) {
639 $result[$key] = call_user_func_array(array($object, $method), $args);
646 * Trims delimiters from a string and then splits it using explode().
648 * This method works mostly like PHP's built-in explode(), except that
649 * surrounding delimiters are trimmed before explode() is called.
651 * Also, if an array or NULL is passed as the $values parameter, the value is
652 * returned unmodified rather than being passed to explode().
654 * @param array|null|string $values
655 * The input string (or an array, or NULL).
656 * @param string $delim
657 * (optional) The boundary string.
660 * An array of strings produced by explode(), or the unmodified input
663 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
664 if ($values === NULL) {
667 // If we already have an array, no need to continue
668 if (is_array($values)) {
671 // Empty string -> empty array
672 if ($values === '') {
675 return explode($delim, trim((string) $values, $delim));
679 * Joins array elements with a string, adding surrounding delimiters.
681 * This method works mostly like PHP's built-in implode(), but the generated
682 * string is surrounded by delimiter characters. Also, if NULL is passed as
683 * the $values parameter, NULL is returned.
685 * @param mixed $values
686 * Array to be imploded. If a non-array is passed, it will be cast to an
688 * @param string $delim
689 * Delimiter to be used for implode() and which will surround the output
692 * @return string|NULL
693 * The generated string, or NULL if NULL was passed as $values parameter.
695 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
696 if ($values === NULL) {
699 // If we already have a string, strip $delim off the ends so it doesn't get added twice
700 if (is_string($values)) {
701 $values = trim($values, $delim);
703 return $delim . implode($delim, (array) $values) . $delim;
707 * Modifies a key in an array while preserving the key order.
709 * By default when an element is added to an array, it is added to the end.
710 * This method allows for changing an existing key while preserving its
711 * position in the array.
713 * The array is both modified in-place and returned.
715 * @param array $elementArray
716 * Array to manipulate.
717 * @param string $oldKey
718 * Old key to be replaced.
719 * @param string $newKey
720 * Replacement key string.
723 * Throws a generic Exception if $oldKey is not found in $elementArray.
726 * The manipulated array.
728 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
729 $keys = array_keys($elementArray);
730 if (FALSE === $index = array_search($oldKey, $keys)) {
731 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
733 $keys[$index] = $newKey;
734 $elementArray = array_combine($keys, array_values($elementArray));
735 return $elementArray;
739 * Searches array keys by regex, returning the value of the first match.
741 * Given a regular expression and an array, this method searches the keys
742 * of the array using the regular expression. The first match is then used
743 * to index into the array, and the associated value is retrieved and
744 * returned. If no matches are found, or if something other than an array
745 * is passed, then a default value is returned. Unless otherwise specified,
746 * the default value is NULL.
748 * @param string $regexKey
749 * The regular expression to use when searching for matching keys.
751 * The array whose keys will be searched.
752 * @param mixed $default
753 * (optional) The default value to return if the regex does not match an
754 * array key, or if something other than an array is passed.
759 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
760 if (is_array($list) && $regexKey) {
761 $matches = preg_grep($regexKey, array_keys($list));
762 $key = reset($matches);
763 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
769 * Generates the Cartesian product of zero or more vectors.
771 * @param array $dimensions
772 * List of dimensions to multiply.
773 * Each key is a dimension name; each value is a vector.
774 * @param array $template
775 * (optional) A base set of values included in every output.
778 * Each item is a distinct combination of values from $dimensions.
780 * For example, the product of
783 * bg => {white, black}
787 * {fg => red, bg => white},
788 * {fg => red, bg => black},
789 * {fg => blue, bg => white},
790 * {fg => blue, bg => black}
793 public static function product($dimensions, $template = array()) {
794 if (empty($dimensions)) {
795 return array($template);
798 foreach ($dimensions as $key => $value) {
800 $firstValues = $value;
803 unset($dimensions[$key]);
806 foreach ($firstValues as $firstValue) {
807 foreach (self
::product($dimensions, $template) as $result) {
808 $result[$firstKey] = $firstValue;
809 $results[] = $result;
817 * Get the first element of an array.
819 * @param array $array
822 public static function first($array) {
823 foreach ($array as $value) {
830 * Extract any $keys from $array and copy to a new array.
832 * Note: If a $key does not appear in $array, then it will
833 * not appear in the result.
835 * @param array $array
837 * List of keys to copy.
840 public static function subset($array, $keys) {
842 foreach ($keys as $key) {
843 if (isset($array[$key])) {
844 $result[$key] = $array[$key];
851 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
852 * This is necessary to preserve sort order when sending an array through json_encode.
854 * @param array $associative
855 * @param string $keyName
856 * @param string $valueName
859 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
861 foreach ($associative as $key => $val) {
862 $output[] = array($keyName => $key, $valueName => $val);
868 * Diff multidimensional arrays
869 * (array_diff does not support multidimensional array)
871 * @param array $array1
872 * @param array $array2
875 public static function multiArrayDiff($array1, $array2) {
876 $arrayDiff = array();
877 foreach ($array1 as $mKey => $mValue) {
878 if (array_key_exists($mKey, $array2)) {
879 if (is_array($mValue)) {
880 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
881 if (count($recursiveDiff)) {
882 $arrayDiff[$mKey] = $recursiveDiff;
886 if ($mValue != $array2[$mKey]) {
887 $arrayDiff[$mKey] = $mValue;
892 $arrayDiff[$mKey] = $mValue;
899 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
901 * @param array $matrix
902 * All matrix data, as a list of rows.
903 * @param array $columns
904 * List of column names.
907 public static function filterColumns($matrix, $columns) {
909 foreach ($matrix as $pos => $oldRow) {
911 foreach ($columns as $column) {
912 $newRow[$column] = CRM_Utils_Array
::value($column, $oldRow);
914 $newRows[$pos] = $newRow;
920 * Rewrite the keys in an array by filtering through a function.
922 * @param array $array
923 * @param callable $func
924 * Function($key, $value). Returns the new key.
927 public static function rekey($array, $func) {
929 foreach ($array as $key => $value) {
930 $newKey = $func($key, $value);
931 $result[$newKey] = $value;
937 * Copy all properties of $other into $array (recursively).
939 * @param array|ArrayAccess $array
940 * @param array $other
942 public static function extend(&$array, $other) {
943 foreach ($other as $key => $value) {
944 if (is_array($value)) {
945 self
::extend($array[$key], $value);
948 $array[$key] = $value;
954 * Get a single value from an array-tre.
957 * Ex: array('foo'=>array('bar'=>123)).
958 * @param array $pathParts
959 * Ex: array('foo',bar').
963 public static function pathGet($arr, $pathParts) {
965 foreach ($pathParts as $part) {
966 if (!isset($r[$part])) {
975 * Set a single value in an array tree.
978 * Ex: array('foo'=>array('bar'=>123)).
979 * @param array $pathParts
980 * Ex: array('foo',bar').
984 public static function pathSet(&$arr, $pathParts, $value) {
986 $last = array_pop($pathParts);
987 foreach ($pathParts as $part) {
988 if (!isset($r[$part])) {
997 * Convert a simple dictionary into separate key+value records.
999 * @param array $array
1000 * Ex: array('foo' => 'bar').
1001 * @param string $keyField
1003 * @param string $valueField
1007 * 0 => array('key' => 'foo', 'value' => 'bar')
1010 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1012 foreach ($array as $key => $value) {
1015 $valueField => $value,