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
|
22 |
|
$results = []; |
19
|
|
|
|
20
|
22 |
|
if (Arr::isAssoc((array) $array)) { |
21
|
22 |
|
foreach ($array as $key => $value) { |
22
|
22 |
|
if (is_iterable($value) && ! empty($value)) { |
23
|
6 |
|
$dot = ''; |
24
|
6 |
|
if (Arr::isAssoc($value)) { |
25
|
2 |
|
$dot = '.'; |
26
|
|
|
} |
27
|
6 |
|
$results = array_merge($results, associativeFlatten($value, $prepend . $key . $dot)); |
28
|
|
|
|
29
|
6 |
|
continue; |
30
|
|
|
} |
31
|
22 |
|
$results[$prepend . $key] = $value; |
32
|
|
|
} |
33
|
22 |
|
return $results; |
34
|
|
|
} |
35
|
6 |
|
$results[$prepend] = $array; |
36
|
6 |
|
return $results; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (! function_exists('isDotString')) { |
41
|
|
|
function isDotString(string $string): bool |
42
|
|
|
{ |
43
|
|
|
return (bool) strpos($string, '.'); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if (! function_exists('renameArrayKey')) { |
48
|
|
|
/** |
49
|
81 |
|
* @param array<mixed> $array |
50
|
81 |
|
* @param string|int $oldKey |
51
|
81 |
|
* @param string|int $newKey |
52
|
81 |
|
* @return array<mixed> |
53
|
|
|
*/ |
54
|
|
|
function renameArrayKey(array &$array, string|int $oldKey, string|int $newKey): array |
55
|
81 |
|
{ |
56
|
|
|
if (array_key_exists($oldKey, $array)) { |
57
|
|
|
$keys = array_keys($array); |
58
|
|
|
$keys[array_search($oldKey, $keys)] = $newKey; |
59
|
|
|
$array = array_combine($keys, $array); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $array; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|