Passed
Push — next ( 230762...ff9bff )
by Bas
08:27
created

associativeFlatten()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 21
rs 9.2222
cc 6
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
use Illuminate\Support\Arr;
6
7
if (! function_exists('associativeFlatten')) {
8
    /**
9
     * Flatten a multi-dimensional associative array with dots.
10
     * List arrays are left untouched
11
     *
12
     * @param  iterable  $array
13
     * @param  string  $prepend
14
     * @return array
15
     */
16
    function associativeFlatten(iterable $array, string $prepend = ''): iterable
17
    {
18
        $results = [];
19
20
        if (Arr::isAssoc((array) $array)) {
21
            foreach ($array as $key => $value) {
22
                if (is_iterable($value) && ! empty($value)) {
23
                    $dot = '';
24
                    if (Arr::isAssoc($value)) {
25
                        $dot = '.';
26
                    }
27
                    $results = array_merge($results, associativeFlatten($value, $prepend . $key . $dot));
28
29
                    continue;
30
                }
31
                $results[$prepend . $key] = $value;
32
            }
33
            return $results;
34
        }
35
        $results[$prepend] = $array;
36
        return $results;
37
    }
38
}
39