Fix #20306: Add new yii\helpers\ArrayHelper::flatten() method

This commit is contained in:
Kairat Jenishev
2025-01-06 20:53:58 +06:00
committed by GitHub
parent 3fc7e71c67
commit f94017ce4c
6 changed files with 452 additions and 49 deletions

View File

@@ -1043,4 +1043,61 @@ class BaseArrayHelper
return $array;
}
/**
* Flattens a multidimensional array into a one-dimensional array.
*
* This method recursively traverses the input array and concatenates the keys
* in a dot format to form a new key in the resulting array.
*
* Example:
*
* ```php
* $array = [
* 'A' => [1, 2],
* 'B' => [
* 'C' => 1,
* 'D' => 2,
* ],
* 'E' => 1,
* ];
* $result = \yii\helpers\ArrayHelper::flatten($array);
* // $result will be:
* // [
* // 'A.0' => 1
* // 'A.1' => 2
* // 'B.C' => 1
* // 'B.D' => 2
* // 'E' => 1
* // ]
* ```
*
* @param array $array the input array to be flattened in terms of name-value pairs.
* @param string $separator the separator to use between keys. Defaults to '.'.
*
* @return array the flattened array.
* @throws InvalidArgumentException if `$array` is neither traversable nor an array.
*/
public static function flatten($array, $separator = '.'): array
{
if (!static::isTraversable($array)) {
throw new InvalidArgumentException('Argument $array must be an array or implement Traversable');
}
$result = [];
foreach ($array as $key => $value) {
$newKey = $key;
if (is_array($value)) {
$flattenedArray = self::flatten($value, $separator);
foreach ($flattenedArray as $subKey => $subValue) {
$result[$newKey . $separator . $subKey] = $subValue;
}
} else {
$result[$newKey] = $value;
}
}
return $result;
}
}