mirror of
https://github.com/yiisoft/yii2.git
synced 2025-12-16 03:28:56 +08:00
Fix #20306: Add new yii\helpers\ArrayHelper::flatten() method
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user