ccd61ba88903e2cae8a89310316f99d32f3a1e6c
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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.
236 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
237 foreach ($list as $name => $value) {
238 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
239 if (is_array($value)) {
240 self
::flatten($value, $flat, $newPrefix, $seperator);
243 if (!empty($value)) {
244 $flat[$newPrefix] = $value;
251 * Converts an array with path-like keys into a tree of arrays.
253 * This function is the inverse of CRM_Utils_Array::flatten().
255 * @param string $delim
258 * A one-dimensional array indexed by string keys
264 public function unflatten($delim, &$arr) {
266 foreach ($arr as $key => $value) {
267 $path = explode($delim, $key);
269 while (count($path) > 1) {
270 $key = array_shift($path);
271 if (!isset($node[$key])) {
272 $node[$key] = array();
274 $node = &$node[$key];
277 $key = array_shift($path);
278 $node[$key] = $value;
286 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
287 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
288 * exist but they are not both arrays, the value from $a1 overrides the
289 * value from $a2 and the value from $a2 is discarded.
292 * First array to be merged.
294 * Second array to be merged.
299 public static function crmArrayMerge($a1, $a2) {
309 foreach ($a1 as $key => $value) {
310 if (array_key_exists($key, $a2) &&
311 is_array($a2[$key]) && is_array($a1[$key])
313 $a3[$key] = array_merge($a1[$key], $a2[$key]);
316 $a3[$key] = $a1[$key];
320 foreach ($a2 as $key => $value) {
321 if (array_key_exists($key, $a1)) {
322 // already handled in above loop
325 $a3[$key] = $a2[$key];
332 * Determines whether an array contains any sub-arrays.
335 * The array to inspect.
338 * True if $list contains at least one sub-array, false otherwise.
340 public static function isHierarchical(&$list) {
341 foreach ($list as $n => $v) {
352 * @return bool TRUE if $subset is a subset of $superset
354 public static function isSubset($subset, $superset) {
355 foreach ($subset as $expected) {
356 if (!in_array($expected, $superset)) {
364 * Searches an array recursively in an optionally case-insensitive manner.
366 * @param string $value
367 * Value to search for.
368 * @param array $params
369 * Array to search within.
370 * @param bool $caseInsensitive
371 * (optional) Whether to search in a case-insensitive manner.
374 * True if $value was found, false otherwise.
377 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
378 foreach ($params as $item) {
379 if (is_array($item)) {
380 $ret = crmInArray($value, $item, $caseInsensitive);
383 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
393 * This function is used to convert associative array names to values
396 * This function is used by both the web form layer and the api. Note that
397 * the api needs the name => value conversion, also the view layer typically
398 * requires value => name conversion
400 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
401 $id = $property . '_id';
403 $src = $reverse ?
$property : $id;
404 $dst = $reverse ?
$id : $property;
406 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
410 $look = $reverse ?
array_flip($lookup) : $lookup;
412 //trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
414 foreach ($look as $k => $v) {
415 $newLook[trim($k, ".")] = $v;
420 if (is_array($look)) {
421 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
426 $tempLook = array_change_key_case($look, CASE_LOWER
);
428 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
433 * Checks whether an array is empty.
435 * An array is empty if its values consist only of NULL and empty sub-arrays.
436 * Containing a non-NULL value or non-empty array makes an array non-empty.
438 * If something other than an array is passed, it is considered to be empty.
440 * If nothing is passed at all, the default value provided is empty.
442 * @param array $array
443 * (optional) Array to be checked for emptiness.
446 * True if the array is empty.
448 public static function crmIsEmptyArray($array = array()) {
449 if (!is_array($array)) {
452 foreach ($array as $element) {
453 if (is_array($element)) {
454 if (!self
::crmIsEmptyArray($element)) {
458 elseif (isset($element)) {
466 * Sorts an associative array of arrays by an attribute using strnatcmp().
468 * @param array $array
469 * Array to be sorted.
470 * @param string $field
471 * Name of the attribute used for sorting.
476 public static function crmArraySortByField($array, $field) {
477 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
478 uasort($array, create_function('$a,$b', $code));
483 * Recursively removes duplicate values from a multi-dimensional array.
485 * @param array $array
486 * The input array possibly containing duplicate values.
489 * The input array with duplicate values removed.
491 public static function crmArrayUnique($array) {
492 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
493 foreach ($result as $key => $value) {
494 if (is_array($value)) {
495 $result[$key] = self
::crmArrayUnique($value);
502 * Sorts an array and maintains index association (with localization).
504 * Uses Collate from the PECL "intl" package, if available, for UTF-8
505 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
507 * On Debian/Ubuntu: apt-get install php5-intl
509 * @param array $array
510 * (optional) Array to be sorted.
515 public static function asort($array = array()) {
516 $lcMessages = CRM_Utils_System
::getUFLocale();
518 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
519 $collator = new Collator($lcMessages . '.utf8');
520 $collator->asort($array);
523 // This calls PHP's built-in asort().
531 * Unsets an arbitrary list of array elements from an associative array.
533 * @param array $items
534 * The array from which to remove items.
536 * @internal param string|\string[] $key When passed a string, unsets $items[$key].* When passed a string, unsets $items[$key].
537 * When passed an array of strings, unsets $items[$k] for each string $k
540 public static function remove(&$items) {
541 foreach (func_get_args() as $n => $key) {
542 // Skip argument 0 ($items) by testing $n for truth.
543 if ($n && is_array($key)) {
544 foreach($key as $k) {
555 * Builds an array-tree which indexes the records in an array.
557 * @param string[] $keys
558 * Properties by which to index.
559 * @param object|array $records
562 * Multi-dimensional array, with one layer for each key.
564 public static function index($keys, $records) {
565 $final_key = array_pop($keys);
568 foreach ($records as $record) {
570 foreach ($keys as $key) {
571 if (is_array($record)) {
572 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
574 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
576 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
577 $node[$keyvalue] = array();
579 $node = &$node[$keyvalue];
581 if (is_array($record)) {
582 $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};
608 $result[$key] = $record[$prop];
616 * Trims delimiters from a string and then splits it using explode().
618 * This method works mostly like PHP's built-in explode(), except that
619 * surrounding delimiters are trimmed before explode() is called.
621 * Also, if an array or NULL is passed as the $values parameter, the value is
622 * returned unmodified rather than being passed to explode().
624 * @param array|null|string $values
625 * The input string (or an array, or NULL).
626 * @param string $delim
627 * (optional) The boundary string.
630 * An array of strings produced by explode(), or the unmodified input
633 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
634 if ($values === NULL) {
637 // If we already have an array, no need to continue
638 if (is_array($values)) {
641 return explode($delim, trim((string) $values, $delim));
645 * Joins array elements with a string, adding surrounding delimiters.
647 * This method works mostly like PHP's built-in implode(), but the generated
648 * string is surrounded by delimiter characters. Also, if NULL is passed as
649 * the $values parameter, NULL is returned.
651 * @param mixed $values
652 * Array to be imploded. If a non-array is passed, it will be cast to an
654 * @param string $delim
655 * Delimiter to be used for implode() and which will surround the output
658 * @return string|NULL
659 * The generated string, or NULL if NULL was passed as $values parameter.
661 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
662 if ($values === NULL) {
665 // If we already have a string, strip $delim off the ends so it doesn't get added twice
666 if (is_string($values)) {
667 $values = trim($values, $delim);
669 return $delim . implode($delim, (array) $values) . $delim;
673 * Modifies a key in an array while preserving the key order.
675 * By default when an element is added to an array, it is added to the end.
676 * This method allows for changing an existing key while preserving its
677 * position in the array.
679 * The array is both modified in-place and returned.
681 * @param array $elementArray
682 * Array to manipulate.
683 * @param string $oldKey
684 * Old key to be replaced.
685 * @param string $newKey
686 * Replacement key string.
689 * Throws a generic Exception if $oldKey is not found in $elementArray.
692 * The manipulated array.
694 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
695 $keys = array_keys($elementArray);
696 if (FALSE === $index = array_search($oldKey, $keys)) {
697 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
699 $keys[$index] = $newKey;
700 $elementArray = array_combine($keys, array_values($elementArray));
701 return $elementArray;
705 * Searches array keys by regex, returning the value of the first match.
707 * Given a regular expression and an array, this method searches the keys
708 * of the array using the regular expression. The first match is then used
709 * to index into the array, and the associated value is retrieved and
710 * returned. If no matches are found, or if something other than an array
711 * is passed, then a default value is returned. Unless otherwise specified,
712 * the default value is NULL.
714 * @param string $regexKey
715 * The regular expression to use when searching for matching keys.
717 * The array whose keys will be searched.
718 * @param mixed $default
719 * (optional) The default value to return if the regex does not match an
720 * array key, or if something other than an array is passed.
728 * @param null $default
732 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
733 if (is_array($list) && $regexKey) {
734 $matches = preg_grep($regexKey, array_keys($list));
735 $key = reset($matches);
736 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
742 * Generates the Cartesian product of zero or more vectors.
744 * @param array $dimensions
745 * List of dimensions to multiply.
746 * Each key is a dimension name; each value is a vector.
747 * @param array $template
748 * (optional) A base set of values included in every output.
751 * Each item is a distinct combination of values from $dimensions.
753 * For example, the product of
756 * bg => {white, black}
760 * {fg => red, bg => white},
761 * {fg => red, bg => black},
762 * {fg => blue, bg => white},
763 * {fg => blue, bg => black}
766 public static function product($dimensions, $template = array()) {
767 if (empty($dimensions)) {
768 return array($template);
771 foreach ($dimensions as $key => $value) {
773 $firstValues = $value;
776 unset($dimensions[$key]);
779 foreach ($firstValues as $firstValue) {
780 foreach (self
::product($dimensions, $template) as $result) {
781 $result[$firstKey] = $firstValue;
782 $results[] = $result;
790 * Get the first element of an array
792 * @param array $array
795 public static function first($array) {
796 foreach ($array as $value) {
803 * Extract any $keys from $array and copy to a new array.
805 * Note: If a $key does not appear in $array, then it will
806 * not appear in the result.
808 * @param array $array
810 * List of keys to copy.
813 public static function subset($array, $keys) {
815 foreach ($keys as $key) {
816 if (isset($array[$key])) {
817 $result[$key] = $array[$key];
824 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
825 * This is necessary to preserve sort order when sending an array through json_encode.
827 * @param array $associative
828 * @param string $keyName
829 * @param string $valueName
832 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
834 foreach ($associative as $key => $val) {
835 $output[] = array($keyName => $key, $valueName => $val);