-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharraymethods.php
89 lines (75 loc) · 2.39 KB
/
arraymethods.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace Framework {
/**
* Utility methods for working with the basic data types we find in PHP
*/
class ArrayMethods {
private function __construct() {
# code...
}
private function __clone() {
//do nothing
}
/**
* Useful for converting a multidimensional array into a unidimensional array.
*
* @param type $array
* @param type $return
* @return type
*/
public static function flatten($array, $return = array()) {
foreach ($array as $key => $value) {
if (is_array($value) || is_object($value)) {
$return = self::flatten($value, $return);
} else {
$return[] = $value;
}
}
return $return;
}
public static function first($array) {
if (sizeof($array) == 0) {
return null;
}
$keys = array_keys($array);
return $array[$keys[0]];
}
public static function last($array) {
if (sizeof($array) == 0) {
return null;
}
$keys = array_keys($array);
return $array[$keys[sizeof($keys) - 1]];
}
public static function toObject($array) {
$result = new \stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result->{$key} = self::toObject($value);
} else {
$result->{$key} = $value;
}
} return $result;
}
/**
* Removes all values considered empty() and returns the resultant array
* @param type $array
* @return type the resultant array
*/
public static function clean($array) {
return array_filter($array, function ($item) {
return !empty($item);
});
}
/**
* Returns an array, which contains all the items of the initial array, after they have been trimmed of all whitespace.
* @param type $array
* @return type array trimmed
*/
public static function trim($array) {
return array_map(function ($item) {
return trim($item);
}, $array);
}
}
}