You are here

protected static function WebformArrayHelper::flattenAssocRecursive in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Utility/WebformArrayHelper.php \Drupal\webform\Utility\WebformArrayHelper::flattenAssocRecursive()

TTraverse an associative array and collect references to all key/value pairs in an associative array.

Parameters

array $build: An array.

array $array: An empty array that will be populated with references to key/value pairs.

array $duplicate_array_keys: An array used to track key/value pairs with duplicate keys.

1 call to WebformArrayHelper::flattenAssocRecursive()
WebformArrayHelper::flattenAssoc in src/Utility/WebformArrayHelper.php
Traverse an associative array and collect references to all key/value pairs in an associative array.

File

src/Utility/WebformArrayHelper.php, line 317

Class

WebformArrayHelper
Provides helper to operate on arrays.

Namespace

Drupal\webform\Utility

Code

protected static function flattenAssocRecursive(array &$build, array &$array, array &$duplicate_array_keys) {
  foreach ($build as $key => &$item) {

    // If there are duplicate array keys create an array of referenced
    // key/value pairs.
    if (isset($array[$key])) {

      // If this is the second key/value pairs, we need to restructure to
      // first key/value's reference to be an array of references.
      if (empty($duplicate_array_keys[$key])) {

        // Store a temporary references to the first key/value pair.
        $first_element =& $array[$key];

        // Use unset() to break the reference.
        unset($array[$key]);

        // Create an array of element references.
        $array[$key] = [];

        // Append the first to the array of key/value references.
        $array[$key][] =& $first_element;
      }

      // Now append the current key/value pair to array of key/value pair
      // references.
      $array[$key][] =& $build[$key];

      // Finally track key/value pairs with duplicate keys.
      $duplicate_array_keys[$key] = TRUE;
    }
    else {
      $array[$key] =& $build[$key];
    }
    if (is_array($item)) {
      self::flattenAssocRecursive($item, $array, $duplicate_array_keys);
    }
  }
}