Further utility on handling odd array structure
authoreileen <emcnaughton@wikimedia.org>
Thu, 24 May 2018 03:31:21 +0000 (15:31 +1200)
committereileen <emcnaughton@wikimedia.org>
Thu, 24 May 2018 03:31:21 +0000 (15:31 +1200)
CRM/Utils/Array.php
tests/phpunit/CRM/Utils/ArrayTest.php

index 4829078fc043dabbe7eceacc001bc6c5abf894e4..f4938febf89bfe95ae21931c55d724e10b18a98b 100644 (file)
@@ -1197,4 +1197,20 @@ class CRM_Utils_Array {
     return $array;
   }
 
+  /**
+   * Append the value to the array using the key provided.
+   *
+   * e.g if value is 'llama' & path is [0, 'email', 'location'] result will be
+   * [0 => ['email' => ['location' => 'llama']]
+   *
+   * @param $path
+   * @param $value
+   *
+   * @return array
+   */
+  public static function recursiveBuild($path, $value) {
+    $arrayKey = array_shift($path);
+    return [$arrayKey => (empty($path) ? $value : self::recursiveBuild($path, $value))];
+  }
+
 }
index 1c32c0c681328ead1978be7d32863becbc11bd01..34d9d6c30ab20261dfd0982a3ae2069009400ddc 100644 (file)
@@ -298,4 +298,28 @@ class CRM_Utils_ArrayTest extends CiviUnitTestCase {
     $this->assertEquals($expected, $result);
   }
 
+  /**
+   * Get values for build test.
+   */
+  public function getBuildValueExamples() {
+    return [
+      [
+        [0, 'email', 2, 'location'], [0 => ['email' => [2 => ['location' => 'llama']]]]
+      ]
+    ];
+  }
+
+  /**
+   * Test the build recursive function.
+   *
+   * @param $path
+   * @param $expected
+   *
+   * @dataProvider getBuildValueExamples
+   */
+  public function testBuildRecursiveValue($path, $expected) {
+    $result = CRM_Utils_Array::recursiveBuild($path, 'llama');
+    $this->assertEquals($expected, $result);
+  }
+
 }