1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace N98\Util; |
4
|
|
|
|
5
|
|
|
class ArrayFunctions |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Merge two arrays together. |
9
|
|
|
* |
10
|
|
|
* If an integer key exists in both arrays, the value from the second array |
11
|
|
|
* will be appended the the first array. If both values are arrays, they |
12
|
|
|
* are merged together, else the value of the second array overwrites the |
13
|
|
|
* one of the first array. |
14
|
|
|
* |
15
|
|
|
* @see http://packages.zendframework.com/docs/latest/manual/en/index.html#zend-stdlib |
16
|
|
|
* @param array $a |
17
|
|
|
* @param array $b |
18
|
|
|
* @return array |
19
|
|
|
*/ |
20
|
|
|
public static function mergeArrays(array $a, array $b) |
21
|
|
|
{ |
22
|
|
|
foreach ($b as $key => $value) { |
23
|
|
|
if (array_key_exists($key, $a)) { |
24
|
|
|
if (is_int($key)) { |
25
|
|
|
$a[] = $value; |
26
|
|
|
} elseif (is_array($value) && is_array($a[$key])) { |
27
|
|
|
$a[$key] = self::mergeArrays($a[$key], $value); |
28
|
|
|
} else { |
29
|
|
|
$a[$key] = $value; |
30
|
|
|
} |
31
|
|
|
} else { |
32
|
|
|
$a[$key] = $value; |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $a; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param array $matrix |
41
|
|
|
* @param string $key key to filter |
42
|
|
|
* @param mixed $value to compare against (strict comparison) |
43
|
|
|
* @return array |
44
|
|
|
*/ |
45
|
|
|
public static function matrixFilterByValue(array $matrix, $key, $value) |
46
|
|
|
{ |
47
|
|
|
return self::matrixCallbackFilter($matrix, function (array $item) use ($key, $value) { |
48
|
|
|
return $item[$key] !== $value; |
49
|
|
|
}); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param array $matrix |
54
|
|
|
* @param string $key to filter |
55
|
|
|
* @param string $value to compare against |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
|
|
public static function matrixFilterStartswith(array $matrix, $key, $value) |
59
|
|
|
{ |
60
|
|
|
return self::matrixCallbackFilter($matrix, function (array $item) use ($key, $value) { |
61
|
|
|
return strncmp($item[$key], $value, strlen($value)); |
62
|
|
|
}); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param array $matrix |
67
|
|
|
* @param callable $callback that when return true on the row will unset it |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
|
|
private static function matrixCallbackFilter(array $matrix, $callback) |
71
|
|
|
{ |
72
|
|
|
foreach ($matrix as $k => $item) { |
73
|
|
|
if ($callback($item)) { |
74
|
|
|
unset($matrix[$k]); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $matrix; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|