From 2c6fe88ac31dbb981097402c3f78cdd8af169088 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Sat, 29 Aug 2015 07:54:38 -0700 Subject: [PATCH] CRM_Utils_Array::collectMethod() and ::toKeyValueRows() --- CRM/Utils/Array.php | 54 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/CRM/Utils/Array.php b/CRM/Utils/Array.php index 74ae8aa81a..e5835dadbe 100644 --- a/CRM/Utils/Array.php +++ b/CRM/Utils/Array.php @@ -613,6 +613,35 @@ class CRM_Utils_Array { return $result; } + /** + * Iterates over a list of objects and executes some method on each. + * + * Comparison: + * - This is like array_map(), except it executes the objects' method + * instead of a free-form callable. + * - This is like Array::collect(), except it uses a method + * instead of a property. + * + * @param string $method + * The method to execute. + * @param array|Traversable $objects + * A list of objects. + * @param array $args + * An optional list of arguments to pass to the method. + * + * @return array + * Keys are the original keys of $objects; values are the method results. + */ + public static function collectMethod($method, $objects, $args = array()) { + $result = array(); + if (is_array($objects)) { + foreach ($objects as $key => $object) { + $result[$key] = call_user_func_array(array($object, $method), $args); + } + } + return $result; + } + /** * Trims delimiters from a string and then splits it using explode(). * @@ -964,4 +993,29 @@ class CRM_Utils_Array { $r[$last] = $value; } + /** + * Convert a simple dictionary into separate key+value records. + * + * @param array $array + * Ex: array('foo' => 'bar'). + * @param string $keyField + * Ex: 'key'. + * @param string $valueField + * Ex: 'value'. + * @return array + * Ex: array( + * 0 => array('key' => 'foo', 'value' => 'bar') + * ). + */ + public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') { + $result = array(); + foreach ($array as $key => $value) { + $result[] = array( + $keyField => $key, + $valueField => $value, + ); + } + return $result; + } + } -- 2.25.1