1
|
|
|
<?php namespace Arcanedev\Composer\Utilities; |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Class NestedArray |
5
|
|
|
* |
6
|
|
|
* @package Arcanedev\Composer\Utilities |
7
|
|
|
* @author ARCANEDEV <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
class NestedArray |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Merges multiple arrays, recursively, and returns the merged array. |
13
|
|
|
* |
14
|
|
|
* This function is similar to PHP's array_merge_recursive() function, but it handles non-array values differently. |
15
|
|
|
* When merging values that are not both arrays, the latter value replaces the former rather than merging with it. |
16
|
|
|
* |
17
|
|
|
* |
18
|
|
|
* @param array $arrays |
19
|
|
|
* |
20
|
|
|
* @return array |
21
|
|
|
* |
22
|
|
|
* @see NestedArray::mergeDeepArray() |
23
|
|
|
*/ |
24
|
9 |
|
public static function mergeDeep(...$arrays) |
25
|
|
|
{ |
26
|
9 |
|
return self::mergeDeepArray($arrays); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Merges multiple arrays, recursively, and returns the merged array. |
31
|
|
|
* |
32
|
|
|
* This function is equivalent to NestedArray::mergeDeep(), except the input arrays are passed as a single array |
33
|
|
|
* parameter rather than a variable parameter list. |
34
|
|
|
* |
35
|
|
|
* @param array $arrays |
36
|
|
|
* @param bool $preserveIntegerKeys |
37
|
|
|
* |
38
|
|
|
* @return array |
39
|
|
|
* |
40
|
|
|
* @see NestedArray::mergeDeep() |
41
|
|
|
*/ |
42
|
18 |
|
public static function mergeDeepArray(array $arrays, $preserveIntegerKeys = false) |
43
|
|
|
{ |
44
|
18 |
|
$result = []; |
45
|
|
|
|
46
|
18 |
|
foreach ($arrays as $array) { |
47
|
18 |
|
foreach ($array as $key => $value) { |
48
|
|
|
// Renumber integer keys as array_merge_recursive() does unless $preserve_integer_keys is set to TRUE. |
49
|
|
|
// Note that PHP automatically converts array keys that are integer strings (e.g., '1') to integers. |
50
|
18 |
|
if (is_integer($key) && ! $preserveIntegerKeys) { |
51
|
18 |
|
$result[] = $value; |
52
|
|
|
} |
53
|
18 |
|
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) { |
54
|
|
|
// Recurse when both values are arrays. |
55
|
18 |
|
$result[$key] = self::mergeDeepArray([$result[$key], $value], $preserveIntegerKeys); |
56
|
|
|
} |
57
|
|
|
else { |
58
|
|
|
// Otherwise, use the latter value, overriding any previous value. |
59
|
18 |
|
$result[$key] = $value; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
18 |
|
return $result; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|