1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
class Ajde_Core_Array |
4
|
|
|
{ |
5
|
|
|
/** |
6
|
|
|
* TODO |
7
|
|
|
* |
8
|
|
|
* @param array $array1 |
9
|
|
|
* @param array $array2 |
10
|
|
|
* @return array |
11
|
|
|
*/ |
12
|
|
|
public static function mergeRecursive(array $array1, array $array2) |
13
|
|
|
{ |
14
|
|
|
$merged = $array1; |
15
|
|
|
|
16
|
|
|
foreach ($array2 as $key => &$value) { |
17
|
|
|
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { |
18
|
|
|
$merged[$key] = self::mergeRecursive($merged[$key], $value); |
19
|
|
|
} else if (is_numeric($key)) { |
20
|
|
|
if (!in_array($value, $merged)) { |
21
|
|
|
$merged[] = $value; |
22
|
|
|
} |
23
|
|
|
} else { |
24
|
|
|
$merged[$key] = $value; |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
return $merged; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Get an item from an array using "dot" notation. |
33
|
|
|
* |
34
|
|
|
* @param array $array |
35
|
|
|
* @param string $key |
36
|
|
|
* @param mixed $default |
37
|
|
|
* @return mixed |
38
|
|
|
*/ |
39
|
|
|
public static function get($array, $key, $default = null) |
40
|
|
|
{ |
41
|
|
|
if (is_null($key)) return $array; |
42
|
|
|
|
43
|
|
|
if (isset($array[$key])) return $array[$key]; |
44
|
|
|
|
45
|
|
|
foreach (explode('.', $key) as $segment) { |
46
|
|
|
if (!is_array($array) || !array_key_exists($segment, $array)) { |
47
|
|
|
return $default; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$array = $array[$segment]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $array; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Set an array item to a given value using "dot" notation. |
58
|
|
|
* |
59
|
|
|
* If no key is given to the method, the entire array will be replaced. |
60
|
|
|
* |
61
|
|
|
* @param array $array |
62
|
|
|
* @param string $key |
63
|
|
|
* @param mixed $value |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
|
|
public static function set(&$array, $key, $value) |
67
|
|
|
{ |
68
|
|
|
if (is_null($key)) return $array = $value; |
69
|
|
|
|
70
|
|
|
$keys = explode('.', $key); |
71
|
|
|
|
72
|
|
|
while (count($keys) > 1) |
73
|
|
|
{ |
74
|
|
|
$key = array_shift($keys); |
75
|
|
|
|
76
|
|
|
// If the key doesn't exist at this depth, we will just create an empty array |
77
|
|
|
// to hold the next value, allowing us to create the arrays to hold final |
78
|
|
|
// values at the correct depth. Then we'll keep digging into the array. |
79
|
|
|
if ( ! isset($array[$key]) || ! is_array($array[$key])) |
80
|
|
|
{ |
81
|
|
|
$array[$key] = array(); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$array =& $array[$key]; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
$array[array_shift($keys)] = $value; |
88
|
|
|
|
89
|
|
|
return $array; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|