Flattening

flatten

Definition

1
Arr::flatten(array $array, ?int $depth = null, bool $assoc = false): array
Copied!

Description

Flatten array of arrays to a n-depth array

Examples

1
$array = [
2
'a' => [
3
'b' => [
4
'c' => 'test'
5
],
6
'd' => 1
7
],
8
'b' => [
9
'e' => 2
10
]
11
];
12
13
Arr::flatten($array) ->
14
[
15
'test',
16
1,
17
2
18
]
19
Arr::flatten($array, 1) ->
20
[
21
['c' => 'test'],
22
1,
23
2
24
]
25
Arr::flatten($array, 0) ->
26
[
27
[
28
'b' => [
29
'c' => 'test'
30
],
31
'd' => 1
32
],
33
[
34
'e' => 2
35
]
36
]
37
38
Arr::flatten([[[[]]]]) -> []
39
40
// When $assoc is set to true this method will try to preserve as much string keys as possible using automatically generated numeric indexes as fallback
41
Arr::flatten($array, null, true) ->
42
[
43
'c' => 'test',
44
'd' => 1,
45
'e' => 2
46
]
47
48
$array = [
49
'a' => [
50
'b' => [
51
'c' => 1,
52
],
53
],
54
[
55
'c' => 2
56
]
57
];
58
59
// Here key 'c' is duplicated so it will fallback to numeric index
60
Arr::flatten($array, null, true) ->
61
[
62
'c' => 1,
63
2,
64
]
Copied!

flattenSingle

Definition

1
Arr::flattenSingle(array $array): array
Copied!

Description

Flatten single element arrays (also nested single element arrays)

Examples

1
$array = [
2
'a' => ['test'],
3
'b' => [
4
'test2',
5
'c' => ['test3']
6
]
7
];
8
9
Arr::flattenSingle($array) ->
10
[
11
'a' => 'test',
12
'b' => [
13
'test2',
14
'c' => 'test3'
15
],
16
]
17
18
$array = [
19
'a' => [
20
'b' => 1
21
],
22
'b' => 2,
23
];
24
25
Arr::flattenSingle($array) -> ['a' => 1, 'b' => 2]
26
27
Arr::flattenSingle([['a']]) -> ['a']
28
29
Arr::flattenSingle([]) -> []
Copied!
Last modified 2yr ago
Copy link