Skip to content

Commit

Permalink
Added "Flattening Arrays" section #20306
Browse files Browse the repository at this point in the history
  • Loading branch information
xcopy committed Jan 5, 2025
1 parent 698eb10 commit 57874b0
Showing 1 changed file with 137 additions and 0 deletions.
137 changes: 137 additions & 0 deletions docs/guide/helper-array.md
Original file line number Diff line number Diff line change
Expand Up @@ -483,3 +483,140 @@ ArrayHelper::isIn('a', new ArrayObject(['a']));
// true
ArrayHelper::isSubset(new ArrayObject(['a', 'c']), new ArrayObject(['a', 'b', 'c']));
```

## Flattening Arrays <span id="flattening-arrays"></span>

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]
```

0 comments on commit 57874b0

Please sign in to comment.