3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Provides a collection of static methods for array manipulation.
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 class CRM_Utils_Array
{
21 * Cast a value to an array.
23 * This is similar to PHP's `(array)`, but it also converts iterators.
28 public static function cast($value) {
29 if (is_array($value)) {
32 if ($value instanceof CRM_Utils_LazyArray ||
$value instanceof ArrayObject
) {
33 // iterator_to_array() would work here, but getArrayCopy() doesn't require actual iterations.
34 return $value->getArrayCopy();
36 if (is_iterable($value)) {
37 return iterator_to_array($value);
39 if (is_scalar($value)) {
42 throw new \
RuntimeException(sprintf("Cannot cast %s to array", gettype($value)));
46 * Returns $list[$key] if such element exists, or a default value otherwise.
48 * If $list is not actually an array at all, then the default value is
49 * returned. We hope to deprecate this behaviour.
53 * Key value to look up in the array.
54 * @param array|ArrayAccess $list
55 * Array from which to look up a value.
56 * @param mixed $default
57 * (optional) Value to return $list[$key] does not exist.
60 * Can return any type, since $list might contain anything.
62 public static function value($key, $list, $default = NULL) {
63 if (is_array($list)) {
64 return array_key_exists($key, $list) ?
$list[$key] : $default;
66 if ($list instanceof ArrayAccess
) {
67 // ArrayAccess requires offsetExists is implemented for the equivalent to array_key_exists.
68 return $list->offsetExists($key) ?
$list[$key] : $default;
70 // @todo - eliminate these from core & uncomment this line.
71 // CRM_Core_Error::deprecatedFunctionWarning('You have passed an invalid parameter for the "list"');
76 * Recursively searches an array for a key, returning the first value found.
78 * If $params[$key] does not exist and $params contains arrays, descend into
79 * each array in a depth-first manner, in array iteration order.
81 * @param array $params
82 * The array to be searched.
84 * The key to search for.
87 * The value of the key, or null if the key is not found.
89 public static function retrieveValueRecursive(array $params, string $key) {
90 // Note that !empty means funky handling for 0
91 // but it is 'baked in'. We should probably deprecate this
92 // for a more logical approach.
93 // see https://github.com/civicrm/civicrm-core/pull/19478#issuecomment-785388559
94 if (!empty($params[$key])) {
97 foreach ($params as $subParam) {
98 if (is_array($subParam) &&
99 // @todo - this will mishandle values like 0 and false
100 // but it's a little scary to fix.
101 $value = self
::retrieveValueRecursive($subParam, $key)
110 * Recursively searches through a given array for all matches
116 public static function findAll($collection, $predicate) {
118 $search = function($collection) use (&$search, &$results, $predicate) {
119 if (is_array($collection)) {
120 if (is_callable($predicate)) {
121 if ($predicate($collection)) {
122 $results[] = $collection;
125 elseif (is_array($predicate)) {
126 if (count(array_intersect_assoc($collection, $predicate)) === count($predicate)) {
127 $results[] = $collection;
131 if (array_key_exists($predicate, $collection)) {
132 $results[] = $collection;
135 foreach ($collection as $item) {
140 $search($collection);
145 * Wraps and slightly changes the behavior of PHP's array_search().
147 * This function reproduces the behavior of array_search() from PHP prior to
148 * version 4.2.0, which was to return NULL on failure. This function also
149 * checks that $list is an array before attempting to search it.
152 * @param mixed $value
153 * The value to search for.
155 * The array to be searched.
157 * @return int|string|null
158 * Returns the key, which could be an int or a string, or NULL on failure.
160 public static function key($value, $list) {
161 if (is_array($list)) {
162 $key = array_search($value, $list);
164 // array_search returns key if found, false otherwise
165 // it may return values like 0 or empty string which
166 // evaluates to false
167 // hence we must use identical comparison operator
168 return ($key === FALSE) ?
NULL : $key;
174 * Builds an XML fragment representing an array.
176 * Depending on the nature of the keys of the array (and its sub-arrays,
177 * if any) the XML fragment may not be valid.
180 * The array to be serialized.
182 * (optional) Indentation depth counter.
183 * @param string $separator
184 * (optional) String to be appended after open/close tags.
187 * XML fragment representing $list.
189 public static function &xml(&$list, $depth = 1, $separator = "\n") {
191 foreach ($list as $name => $value) {
192 $xml .= str_repeat(' ', $depth * 4);
193 if (is_array($value)) {
194 $xml .= "<{$name}>{$separator}";
195 $xml .= self
::xml($value, $depth +
1, $separator);
196 $xml .= str_repeat(' ', $depth * 4);
197 $xml .= "</{$name}>{$separator}";
200 // make sure we escape value
201 $value = self
::escapeXML($value);
202 $xml .= "<{$name}>$value</{$name}>{$separator}";
209 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
211 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
214 * @param string $value
215 * String to be sanitized.
218 * Sanitized version of $value.
220 public static function escapeXML($value) {
225 $src = ['&', '<', '>', '\ 1'];
226 $dst = ['&', '<', '>', ','];
229 return str_replace($src, $dst, $value);
233 * Converts a nested array to a flat array.
235 * The nested structure is preserved in the string values of the keys of the
238 * Example nested array:
263 * Corresponding flattened array:
269 * [asdf.merp] => bleep
270 * [asdf.quack.0] => 1
271 * [asdf.quack.1] => 2
272 * [asdf.quack.2] => 3
277 * Array to be flattened.
280 * @param string $prefix
281 * (optional) String to prepend to keys.
282 * @param string $separator
283 * (optional) String that separates the concatenated keys.
285 public static function flatten(&$list, &$flat, $prefix = '', $separator = ".") {
286 foreach ($list as $name => $value) {
287 $newPrefix = ($prefix) ?
$prefix . $separator . $name : $name;
288 if (is_array($value)) {
289 self
::flatten($value, $flat, $newPrefix, $separator);
292 $flat[$newPrefix] = $value;
298 * Converts an array with path-like keys into a tree of arrays.
300 * This function is the inverse of CRM_Utils_Array::flatten().
302 * @param string $delim
305 * A one-dimensional array indexed by string keys
310 public function unflatten($delim, &$arr) {
312 foreach ($arr as $key => $value) {
313 $path = explode($delim, $key);
315 while (count($path) > 1) {
316 $key = array_shift($path);
317 if (!isset($node[$key])) {
320 $node = &$node[$key];
323 $key = array_shift($path);
324 $node[$key] = $value;
332 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
333 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
334 * exist but they are not both arrays, the value from $a1 overrides the
335 * value from $a2 and the value from $a2 is discarded.
338 * First array to be merged.
340 * Second array to be merged.
345 public static function crmArrayMerge($a1, $a2) {
355 foreach ($a1 as $key => $value) {
356 if (array_key_exists($key, $a2) &&
357 is_array($a2[$key]) && is_array($a1[$key])
359 $a3[$key] = array_merge($a1[$key], $a2[$key]);
362 $a3[$key] = $a1[$key];
366 foreach ($a2 as $key => $value) {
367 if (array_key_exists($key, $a1)) {
368 // already handled in above loop
371 $a3[$key] = $a2[$key];
378 * Determines whether an array contains any sub-arrays.
381 * The array to inspect.
384 * True if $list contains at least one sub-array, false otherwise.
386 public static function isHierarchical(&$list) {
387 foreach ($list as $n => $v) {
396 * Is array A a subset of array B.
398 * @param array $subset
399 * @param array $superset
402 * TRUE if $subset is a subset of $superset
404 public static function isSubset($subset, $superset) {
405 foreach ($subset as $expected) {
406 if (!in_array($expected, $superset)) {
414 * Searches an array recursively in an optionally case-insensitive manner.
416 * @param string $value
417 * Value to search for.
418 * @param array $params
419 * Array to search within.
420 * @param bool $caseInsensitive
421 * (optional) Whether to search in a case-insensitive manner.
424 * True if $value was found, false otherwise.
426 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
427 foreach ($params as $item) {
428 if (is_array($item)) {
429 $ret = self
::crmInArray($value, $item, $caseInsensitive);
432 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
442 * Convert associative array names to values and vice-versa.
444 * This function is used by by import functions and some webforms.
446 * @param array $defaults
447 * @param string $property
453 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
454 $id = $property . '_id';
456 $src = $reverse ?
$property : $id;
457 $dst = $reverse ?
$id : $property;
459 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
463 $look = $reverse ?
array_flip($lookup) : $lookup;
465 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
467 foreach ($look as $k => $v) {
468 $newLook[trim($k, ".")] = $v;
473 if (is_array($look)) {
474 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
479 $tempLook = array_change_key_case($look, CASE_LOWER
);
481 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
486 * Checks whether an array is empty.
488 * An array is empty if its values consist only of NULL and empty sub-arrays.
489 * Containing a non-NULL value or non-empty array makes an array non-empty.
491 * If something other than an array is passed, it is considered to be empty.
493 * If nothing is passed at all, the default value provided is empty.
495 * @param array $array
496 * (optional) Array to be checked for emptiness.
499 * True if the array is empty.
501 public static function crmIsEmptyArray($array = []) {
502 if (!is_array($array)) {
505 foreach ($array as $element) {
506 if (is_array($element)) {
507 if (!self
::crmIsEmptyArray($element)) {
511 elseif (isset($element)) {
519 * Sorts an associative array of arrays by an attribute using strnatcmp().
521 * @param array $array
522 * Array to be sorted.
523 * @param string|array $field
524 * Name of the attribute used for sorting.
529 public static function crmArraySortByField($array, $field) {
530 $fields = (array) $field;
531 uasort($array, function ($a, $b) use ($fields) {
532 foreach ($fields as $f) {
533 $v = strnatcmp($a[$f], $b[$f]);
544 * Recursively removes duplicate values from a multi-dimensional array.
546 * @param array $array
547 * The input array possibly containing duplicate values.
550 * The input array with duplicate values removed.
552 public static function crmArrayUnique($array) {
553 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
554 foreach ($result as $key => $value) {
555 if (is_array($value)) {
556 $result[$key] = self
::crmArrayUnique($value);
563 * Sorts an array and maintains index association (with localization).
565 * Uses Collate from the PECL "intl" package, if available, for UTF-8
566 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
568 * On Debian/Ubuntu: apt-get install php5-intl
570 * @param array $array
571 * (optional) Array to be sorted.
576 public static function asort($array = []) {
577 $lcMessages = CRM_Utils_System
::getUFLocale();
579 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
580 $collator = new Collator($lcMessages . '.utf8');
581 $collator->asort($array);
584 // This calls PHP's built-in asort().
592 * Unsets an arbitrary list of array elements from an associative array.
594 * @param array $items
595 * The array from which to remove items.
598 * When passed a string, unsets $items[$key].
599 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
601 public static function remove(&$items) {
602 foreach (func_get_args() as $n => $key) {
603 // Skip argument 0 ($items) by testing $n for truth.
604 if ($n && is_array($key)) {
605 foreach ($key as $k) {
616 * Builds an array-tree which indexes the records in an array.
618 * @param string[] $keys
619 * Properties by which to index.
620 * @param object|array $records
623 * Multi-dimensional array, with one layer for each key.
625 public static function index($keys, $records) {
626 $final_key = array_pop($keys);
629 foreach ($records as $record) {
631 foreach ($keys as $key) {
632 if (is_array($record)) {
633 $keyvalue = $record[$key] ??
NULL;
636 $keyvalue = $record->{$key} ??
NULL;
638 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
639 $node[$keyvalue] = [];
641 $node = &$node[$keyvalue];
643 if (is_array($record)) {
644 $node[$record[$final_key]] = $record;
647 $node[$record->{$final_key}] = $record;
654 * Iterates over a list of records and returns the value of some property.
656 * @param string $prop
657 * Property to retrieve.
658 * @param array|object $records
662 * Keys are the original keys of $records; values are the $prop values.
664 public static function collect($prop, $records) {
666 if (is_array($records)) {
667 foreach ($records as $key => $record) {
668 if (is_object($record)) {
669 $result[$key] = $record->{$prop};
672 $result[$key] = self
::value($prop, $record);
680 * Iterates over a list of objects and executes some method on each.
683 * - This is like array_map(), except it executes the objects' method
684 * instead of a free-form callable.
685 * - This is like Array::collect(), except it uses a method
686 * instead of a property.
688 * @param string $method
689 * The method to execute.
690 * @param array|Traversable $objects
693 * An optional list of arguments to pass to the method.
696 * Keys are the original keys of $objects; values are the method results.
698 public static function collectMethod($method, $objects, $args = []) {
700 if (is_array($objects)) {
701 foreach ($objects as $key => $object) {
702 $result[$key] = call_user_func_array([$object, $method], $args);
709 * Trims delimiters from a string and then splits it using explode().
711 * This method works mostly like PHP's built-in explode(), except that
712 * surrounding delimiters are trimmed before explode() is called.
714 * Also, if an array or NULL is passed as the $values parameter, the value is
715 * returned unmodified rather than being passed to explode().
717 * @param array|null|string $values
718 * The input string (or an array, or NULL).
719 * @param string $delim
720 * (optional) The boundary string.
723 * An array of strings produced by explode(), or the unmodified input
726 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
727 if ($values === NULL) {
730 // If we already have an array, no need to continue
731 if (is_array($values)) {
734 // Empty string -> empty array
735 if ($values === '') {
738 return explode($delim, trim((string) $values, $delim));
742 * Joins array elements with a string, adding surrounding delimiters.
744 * This method works mostly like PHP's built-in implode(), but the generated
745 * string is surrounded by delimiter characters. Also, if NULL is passed as
746 * the $values parameter, NULL is returned.
748 * @param mixed $values
749 * Array to be imploded. If a non-array is passed, it will be cast to an
751 * @param string $delim
752 * Delimiter to be used for implode() and which will surround the output
755 * @return string|NULL
756 * The generated string, or NULL if NULL was passed as $values parameter.
758 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
759 if ($values === NULL) {
762 // If we already have a string, strip $delim off the ends so it doesn't get added twice
763 if (is_string($values)) {
764 $values = trim($values, $delim);
766 return $delim . implode($delim, (array) $values) . $delim;
770 * Modifies a key in an array while preserving the key order.
772 * By default when an element is added to an array, it is added to the end.
773 * This method allows for changing an existing key while preserving its
774 * position in the array.
776 * The array is both modified in-place and returned.
778 * @param array $elementArray
779 * Array to manipulate.
780 * @param string $oldKey
781 * Old key to be replaced.
782 * @param string $newKey
783 * Replacement key string.
786 * Throws a generic Exception if $oldKey is not found in $elementArray.
789 * The manipulated array.
791 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
792 $keys = array_keys($elementArray);
793 if (FALSE === $index = array_search($oldKey, $keys)) {
794 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
796 $keys[$index] = $newKey;
797 $elementArray = array_combine($keys, array_values($elementArray));
798 return $elementArray;
802 * Searches array keys by regex, returning the value of the first match.
804 * Given a regular expression and an array, this method searches the keys
805 * of the array using the regular expression. The first match is then used
806 * to index into the array, and the associated value is retrieved and
807 * returned. If no matches are found, or if something other than an array
808 * is passed, then a default value is returned. Unless otherwise specified,
809 * the default value is NULL.
811 * @param string $regexKey
812 * The regular expression to use when searching for matching keys.
814 * The array whose keys will be searched.
815 * @param mixed $default
816 * (optional) The default value to return if the regex does not match an
817 * array key, or if something other than an array is passed.
822 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
823 if (is_array($list) && $regexKey) {
824 $matches = preg_grep($regexKey, array_keys($list));
825 $key = reset($matches);
826 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
832 * Generates the Cartesian product of zero or more vectors.
834 * @param array $dimensions
835 * List of dimensions to multiply.
836 * Each key is a dimension name; each value is a vector.
837 * @param array $template
838 * (optional) A base set of values included in every output.
841 * Each item is a distinct combination of values from $dimensions.
843 * For example, the product of
846 * bg => {white, black}
850 * {fg => red, bg => white},
851 * {fg => red, bg => black},
852 * {fg => blue, bg => white},
853 * {fg => blue, bg => black}
856 public static function product($dimensions, $template = []) {
857 if (empty($dimensions)) {
861 foreach ($dimensions as $key => $value) {
863 $firstValues = $value;
866 unset($dimensions[$key]);
869 foreach ($firstValues as $firstValue) {
870 foreach (self
::product($dimensions, $template) as $result) {
871 $result[$firstKey] = $firstValue;
872 $results[] = $result;
880 * Get the first element of an array.
882 * @param array $array
885 public static function first($array) {
886 foreach ($array as $value) {
893 * Extract any $keys from $array and copy to a new array.
895 * Note: If a $key does not appear in $array, then it will
896 * not appear in the result.
898 * @param array $array
900 * List of keys to copy.
903 public static function subset($array, $keys) {
905 foreach ($keys as $key) {
906 if (isset($array[$key])) {
907 $result[$key] = $array[$key];
914 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
915 * This is necessary to preserve sort order when sending an array through json_encode.
917 * @param array $associative
918 * Ex: ['foo' => 'bar'].
919 * @param string $keyName
921 * @param string $valueName
924 * Ex: [0 => ['key' => 'foo', 'value' => 'bar']].
926 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
928 foreach ($associative as $key => $val) {
929 $output[] = [$keyName => $key, $valueName => $val];
935 * Diff multidimensional arrays
936 * (array_diff does not support multidimensional array)
938 * @param array $array1
939 * @param array $array2
942 public static function multiArrayDiff($array1, $array2) {
944 foreach ($array1 as $mKey => $mValue) {
945 if (array_key_exists($mKey, $array2)) {
946 if (is_array($mValue)) {
947 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
948 if (count($recursiveDiff)) {
949 $arrayDiff[$mKey] = $recursiveDiff;
953 if ($mValue != $array2[$mKey]) {
954 $arrayDiff[$mKey] = $mValue;
959 $arrayDiff[$mKey] = $mValue;
966 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
968 * @param array $matrix
969 * All matrix data, as a list of rows.
970 * @param array $columns
971 * List of column names.
974 public static function filterColumns($matrix, $columns) {
976 foreach ($matrix as $pos => $oldRow) {
978 foreach ($columns as $column) {
979 $newRow[$column] = $oldRow[$column] ??
NULL;
981 $newRows[$pos] = $newRow;
987 * Rotate a matrix, converting from row-oriented array to a column-oriented array.
989 * @param iterable $rows
990 * Ex: [['a'=>10,'b'=>'11'], ['a'=>20,'b'=>21]]
991 * Formula: [scalar $rowId => [scalar $colId => mixed $value]]
992 * @param bool $unique
993 * Only return unique values.
995 * Ex: ['a'=>[10,20], 'b'=>[11,21]]
996 * Formula: [scalar $colId => [scalar $rowId => mixed $value]]
997 * Note: In unique mode, the $rowId is not meaningful.
999 public static function asColumns(iterable
$rows, bool $unique = FALSE) {
1001 foreach ($rows as $rowKey => $row) {
1002 foreach ($row as $columnKey => $value) {
1003 if (FALSE === $unique) {
1004 $columns[$columnKey][$rowKey] = $value;
1006 elseif (!in_array($value, $columns[$columnKey] ??
[])) {
1007 $columns[$columnKey][] = $value;
1015 * Rewrite the keys in an array.
1017 * @param array $array
1018 * @param string|callable $indexBy
1019 * Either the value to key by, or a function($key, $value) that returns the new key.
1022 public static function rekey($array, $indexBy) {
1024 foreach ($array as $key => $value) {
1025 $newKey = is_callable($indexBy) ?
$indexBy($key, $value) : $value[$indexBy];
1026 $result[$newKey] = $value;
1032 * Copy all properties of $other into $array (recursively).
1034 * @param array|ArrayAccess $array
1035 * @param array $other
1037 public static function extend(&$array, $other) {
1038 foreach ($other as $key => $value) {
1039 if (is_array($value)) {
1040 self
::extend($array[$key], $value);
1043 $array[$key] = $value;
1049 * Get a single value from an array-tree.
1051 * @param array $values
1052 * Ex: ['foo' => ['bar' => 123]].
1053 * @param array $path
1054 * Ex: ['foo', 'bar'].
1055 * @param mixed $default
1059 public static function pathGet($values, $path, $default = NULL) {
1060 foreach ($path as $key) {
1061 if (!is_array($values) ||
!isset($values[$key])) {
1064 $values = $values[$key];
1070 * Check if a key isset which may be several layers deep.
1072 * This is a helper for when the calling function does not know how many layers deep
1073 * the path array is so cannot easily check.
1075 * @param array $values
1076 * @param array $path
1079 public static function pathIsset($values, $path) {
1080 foreach ($path as $key) {
1081 if (!is_array($values) ||
!isset($values[$key])) {
1084 $values = $values[$key];
1090 * Remove a key from an array.
1092 * This is a helper for when the calling function does not know how many layers deep
1093 * the path array is so cannot easily check.
1095 * @param array $values
1096 * @param array $path
1097 * @param bool $cleanup
1098 * If removed item leaves behind an empty array, should you remove the empty array?
1100 * TRUE if anything has been removed. FALSE if no changes were required.
1102 public static function pathUnset(&$values, $path, $cleanup = FALSE) {
1103 if (count($path) === 1) {
1104 if (isset($values[$path[0]])) {
1105 unset($values[$path[0]]);
1113 $next = array_shift($path);
1114 $r = static::pathUnset($values[$next], $path, $cleanup);
1115 if ($cleanup && $values[$next] === []) {
1117 unset($values[$next]);
1124 * Set a single value in an array tree.
1126 * @param array $values
1127 * Ex: ['foo' => ['bar' => 123]].
1128 * @param array $pathParts
1129 * Ex: ['foo', 'bar'].
1133 public static function pathSet(&$values, $pathParts, $value) {
1135 $last = array_pop($pathParts);
1136 foreach ($pathParts as $part) {
1137 if (!isset($r[$part])) {
1146 * Move an item in an array-tree (if it exists).
1148 * @param array $values
1150 * @param string[] $src
1151 * Old path for the existing item
1152 * @param string[] $dest
1154 * @param bool $cleanup
1156 * Number of items moved (0 or 1).
1158 public static function pathMove(&$values, $src, $dest, $cleanup = FALSE) {
1159 if (!static::pathIsset($values, $src)) {
1163 $value = static::pathGet($values, $src);
1164 static::pathSet($values, $dest, $value);
1165 static::pathUnset($values, $src, $cleanup);
1171 * Attempt to synchronize or fill aliased items.
1173 * If $canonPath is set, copy to $altPath; or...
1174 * If $altPath is set, copy to $canonPath.
1176 * @param array $params
1178 * @param string[] $canonPath
1180 * @param string[] $altPath
1181 * Old/alternate/deprecated path.
1182 * @param callable|null $filter
1183 * Optional function to filter the value as it passes through (canonPath=>altPath or altPath=>canonPath).
1184 * function(mixed $v, bool $isCanon): mixed
1186 public static function pathSync(&$params, $canonPath, $altPath, ?callable
$filter = NULL) {
1187 $MISSING = new \
stdClass();
1189 $v = static::pathGet($params, $canonPath, $MISSING);
1190 if ($v !== $MISSING) {
1191 static::pathSet($params, $altPath, $filter ?
$filter($v, TRUE) : $v);
1195 $v = static::pathGet($params, $altPath, $MISSING);
1196 if ($v !== $MISSING) {
1197 static::pathSet($params, $canonPath, $filter ?
$filter($v, FALSE) : $v);
1203 * Convert a simple dictionary into separate key+value records.
1205 * @param array $array
1206 * Ex: array('foo' => 'bar').
1207 * @param string $keyField
1209 * @param string $valueField
1214 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1215 return self
::makeNonAssociative($array, $keyField, $valueField);
1219 * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values
1220 * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)
1222 * @deprecated use convertCheckboxInputToArray instead (after testing)
1223 * https://github.com/civicrm/civicrm-core/pull/8169
1225 * @param array $array
1227 public static function formatArrayKeys(&$array) {
1228 if (!is_array($array)) {
1231 $keys = array_keys($array, 1);
1232 if (count($keys) > 1 ||
1233 (count($keys) == 1 &&
1234 (current($keys) > 1 ||
1235 is_string(current($keys)) ||
1236 // handle (0 => 4), (1 => 1)
1237 (current($keys) == 1 && $array[1] == 1)
1246 * Convert the data format coming in from checkboxes to an array of values.
1248 * The input format from check boxes looks like
1249 * array('value1' => 1, 'value2' => 1). This function converts those values to
1250 * array(''value1', 'value2).
1252 * The function will only alter the array if all values are equal to 1.
1254 * @param array $input
1258 public static function convertCheckboxFormatToArray($input) {
1259 if (isset($input[0])) {
1262 $keys = array_keys($input, 1);
1263 if ((count($keys) == count($input))) {
1270 * Ensure that array is encoded in utf8 format.
1272 * @param array $array
1274 * @return array $array utf8-encoded.
1276 public static function encode_items($array) {
1277 foreach ($array as $key => $value) {
1278 if (is_array($value)) {
1279 $array[$key] = self
::encode_items($value);
1281 elseif (is_string($value)) {
1282 $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8');
1285 $array[$key] = $value;
1292 * Build tree of elements.
1294 * @param array $elements
1295 * @param int|null $parentId
1299 public static function buildTree($elements, $parentId = NULL) {
1302 foreach ($elements as $element) {
1303 if ($element['parent_id'] == $parentId) {
1304 $children = self
::buildTree($elements, $element['id']);
1306 $element['children'] = $children;
1308 $branch[] = $element;
1316 * Find search string in tree.
1318 * @param string $search
1319 * @param array $tree
1320 * @param string $field
1322 * @return array|null
1324 public static function findInTree($search, $tree, $field = 'id') {
1325 foreach ($tree as $item) {
1326 if ($item[$field] == $search) {
1329 if (!empty($item['children'])) {
1330 $found = self
::findInTree($search, $item['children']);
1340 * Prepend string prefix to every key in an array
1342 * @param array $collection
1343 * @param string $prefix
1346 public static function prefixKeys(array $collection, string $prefix) {
1348 foreach ($collection as $key => $value) {
1349 $result[$prefix . $key] = $value;