flatten()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 5
nop 2
dl 0
loc 18
rs 9.9
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt;
5
6
use RecursiveArrayIterator;
7
use RecursiveIteratorIterator;
8
9
/**
10
 * @param array $items
11
 * @param string|null $pathSeparator
12
 * @return array
13
 */
14
function flatten(array $items, ?string $pathSeparator = null): array
15
{
16
    $result = [];
17
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($items));
18
    foreach ($iterator as $leafValue) {
19
        $keys = [];
20
        foreach (range(0, $iterator->getDepth()) as $depth) {
21
            $keys[] = $iterator->getSubIterator($depth)->key();
22
        }
23
24
        if (! empty($pathSeparator)) {
25
            $result[join($pathSeparator, $keys) ] = $leafValue;
26
        } else {
27
            $result[] = $leafValue;
28
        }
29
    }
30
31
    return $result;
32
}
33