diff --git a/docs/guide/helper-array.md b/docs/guide/helper-array.md index 19c3c03ad5f..e7b1641fff8 100644 --- a/docs/guide/helper-array.md +++ b/docs/guide/helper-array.md @@ -483,3 +483,140 @@ ArrayHelper::isIn('a', new ArrayObject(['a'])); // true ArrayHelper::isSubset(new ArrayObject(['a', 'c']), new ArrayObject(['a', 'b', 'c'])); ``` + +## Flattening Arrays + +The `ArrayHelper::flatten()` method allows you to convert a multi-dimensional array into a single-dimensional array by concatenating keys. + +### Basic Usage + +To flatten a nested array, simply pass the array to the `flatten()` method: + +```php +$array = [ + 'a' => [ + 'b' => [ + 'c' => 1, + 'd' => 2, + ], + 'e' => 3, + ], + 'f' => 4, +]; + +$flattenedArray = ArrayHelper::flatten($array); +// Result: +// [ +// 'a.b.c' => 1, +// 'a.b.d' => 2, +// 'a.e' => 3, +// 'f' => 4, +// ] +``` + +### Custom Separator + +You can specify a custom separator to use when concatenating keys: + +```php +$array = [ + 'a' => [ + 'b' => [ + 'c' => 1, + 'd' => 2, + ], + 'e' => 3, + ], + 'f' => 4, +]; + +$flattenedArray = ArrayHelper::flatten($array, '_'); +// Result: +// [ +// 'a_b_c' => 1, +// 'a_b_d' => 2, +// 'a_e' => 3, +// 'f' => 4, +// ] +``` + +### Handling Special Characters in Keys + +The `flatten()` method can handle keys with special characters: + +```php +$array = [ + 'a.b' => [ + 'c.d' => 1, + ], + 'e.f' => 2, +]; + +$flattenedArray = ArrayHelper::flatten($array); +// Result: +// [ +// 'a.b.c.d' => 1, +// 'e.f' => 2, +// ] +``` + +### Mixed Data Types + +The `flatten()` method works with arrays containing different data types: + +```php +$array = [ + 'a' => [ + 'b' => 'string', + 'c' => 123, + 'd' => true, + 'e' => null, + ], + 'f' => [1, 2, 3], +]; + +$flattenedArray = ArrayHelper::flatten($array); +// Result: +// [ +// 'a.b' => 'string', +// 'a.c' => 123, +// 'a.d' => true, +// 'a.e' => null, +// 'f.0' => 1, +// 'f.1' => 2, +// 'f.2' => 3, +// ] +``` + +### Edge Cases + +The `flatten()` method handles various edge cases, such as empty arrays and non-array values: + +```php +// Empty array +$array = []; +$flattenedArray = ArrayHelper::flatten($array); +// Result: [] + +// Non-array value +$array = 'string'; +$flattenedArray = ArrayHelper::flatten($array); +// Result: +// yii\base\InvalidArgumentException: Argument $array must be an array or implement Traversable +``` + +### Key Collisions + +When keys collide, the `flatten()` method will overwrite the previous value: + +```php +$array = [ + 'a' => [ + 'b' => 1, + ], + 'a.b' => 2, +]; + +$flattenedArray = ArrayHelper::flatten($array); +// Result: ['a.b' => 2] +```